Thursday, September 15, 2011


CORE JAVA
INDEX
1. Class
2. Object
3. Access Spacifier in java
4.Constructor
5. Concept of This (this keyword)
6. Concept of Super (super keyword)
7. Concept of Final (final keyword)
8.. Concept of Abstract Class
9. .Concept of Interface
10.. Concept of Inheritance
12. Overloading of main() in java
13.Concept of Static method
14. Concept of Static Blocks
15. Meaning of factory methods
16.Concept of class loader in java
Class:-
Java classes contain fields and methods. A field is like a C++ data member, and a method is like a C++ member function.

class  Hello
        {
             Public static void main (String[] args)
            {
                       System.out.println (“Hello Java”);
              }
          }
Save the file as an .java extension an compile by the commed prompt like
          javac  <filename>.java
when it is successfully compiled then run it like this
       java <filename>
By convention, class names capitalize the initial of each word.
For example: Employee, Boss, DateUtility, PostOffice, RegularRateCalculator.
This type of naming convention is known as Pascal naming convention.
The other convention, the camel naming convention, capitalizes the initial of each word, except the first word.
Method and field names use the camel naming convention.










Object:-
Basically an class type variable is known as object. Instance of any class is known as object. Object is an runtime entity. In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure. (With the later introduction of object-oriented programming the same word, "object", refers to a particular instance of a class)
Three properties characterize objects:
1. Identity: the property of an object that distinguishes it from other objects
2. State: describes the data stored in the object
3. Behavior: describes the methods in the object's interface by which the object can be used
In computer science, the object lifetime (or life cycle) of an object in object-oriented programming is the time between an object's creation (also known as instantiation or construction) till the object is no longer used, and is destructed or freed.
class objectdemo
{
            int a;
            int b;
            void add(int m,int n)
          {
            a=m;
            b=n;
            int c=m+n;
           System.out.println("value of c:"+c);
}
}

class  main
{
public static void main(String []args)
{
objectdemo o1=new objectdemo();
o1.add(10,20);
}
}




Save it by the name main.java and run.

Access Spacifier in java:-
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. In this way the chance of making accidental mistakes in changing values is minimized. Java allows you to control access to classes, methods, and fields via so-called access specifier. The purpose of access Specifier is to declare which entity cannot be accessed from where. Its effect is different when used on a class.
Access modifiers can be defined at two levels, Class level and member level.
Class level: There are two access Specifier that are valid at the class level. They are
Public and <none>. So, when we define a class, we can do it either of the ways:
Public class a
{
}
OR
Class a
{
}
If a class is defined as public, it can be accessed from outside world i.e. from different
Packages.
If a class is defined w/o any access specifier, it cannot be accessed from different
packages.
Member Level: Member level means for class variables or class methods level.

Class a
{
<access-specifier> int var;
}
class a
{
<access-specifier> void method()
{
}
}
Below is a table showing the effects of access specifiers for class members.
◆ = Can Access. ◇ = No Access.
Specifier
class
subclass
package
world
private
protected
public
(none)


Java offers four access specifiers, listed below in decreasing accessibility:

Public
public classes, methods, and fields can be accessed from everywhere. The only constraint is that a file with Java source code can only contain one public class whose name must also match with the filename. If it exists, this public class represents the application or the applet, in which case the public keyword is necessary to enable your Web browser or applet viewer to show the applet. You use public classes, methods, or fields only if you explicitly want to offer access to these entities and if this access cannot do any harm. An example of a square determined by the position of its upper-left corner and its size:
public class Square {  // public class
  public x, y, size;   // public instance variables
}


Protected
protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package, but not from anywhere else. You use the protected access level when it is appropriate for a class's subclasses to have access to the method or field, but not for unrelated classes.





Default (no specifier)
If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package. This access-level is convenient if you are creating packages. For example, a geometry package that contains Square and Tiling classes, may be easier and cleaner to implement if the coordinates of the upper-left corner of a Square are directly available to the Tiling class but not outside the geometry package.
Private
private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. It is mostly used for encapsulation: data are hidden within the class and accessor methods are provided. An example, in which the position of the upper-left corner of a square can be set or obtained by accessor methods, but individual coordinates are not accessible to the user.








public class Square {   // public class
  private double x, y   // private (encapsulated) instance variables

  public setCorner(int x, int y) {  // setting values of private fields
    this.x = x;
    this.y = y;
  }

  public getCorner() {  // setting values of private fields
    return Point(x, y);
  }
}






Constructor:-
Constructors are used to assign initial values to instance variables of the class. A default constructor with no arguments will be called automatically by the Java Virtual Machine (JVM). Constructor is always called by new operator. Constructor are declared just like as we declare methods, except that the constructor don't have any return type. Constructor can be overloaded provided they should have different arguments because JVM differentiates constructors on the basis of arguments passed in the constructor.Whenever we assign the name of the method same as  class name. Remember this method should not have any return type. This is called as constructor overloading. A constructor is a special method that is used to initialize a newly created object and is  called just after the memory is allocated for the object .It can be used to initialize the objects ,to required ,or default values at the time of object creation.It is not mandatory for the coder to write a constructor for the class.
If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
numeric data types are set to 0
char data types are set to null character(‘\0’)
reference variables are set to null







Example:-
class Demo{
      int  value1;
      int  value2;
      Demo(){  //default constructor
         value1 = 10;
         value2 = 20;
         System.out.println("Inside Constructor");
     }
     public void display(){
        System.out.println("Value1 === "+value1);
        System.out.println("Value2 === "+value2);
    }
   public static void main(String args[]){
       Demo d1 = new Demo();
      d1.display();
  }
}

















Example no.2

class Demo1{
      int  value1;
      int  value2;
      Demo(int a,int b){ // parameterized constructor
         value1 = a;
         value2 = b;
         System.out.println("Inside Constructor");
     }
     public void display(){
        System.out.println("Value1 === "+value1);
        System.out.println("Value2 === "+value2);
    }
   public static void main(String args[]){
       Demo d1 = new Demo(10,20);
      d1.display();
  }
}









Constructor Overloading:-
Constructors can be overloaded just as regular methods. If you have constructor with same name and different arguments then its called constructor overloading
Example:-
class  Constructorover
{
        int a,b;
        Constructorover()
{     
        a=11;
        b=22;
              System.out.println("val a;"+a);
        System.out.println("val b;"+b);    
}
        Constructorover(int a)
        {
        this.a=a;
        b=a;
                System.out.println("val a;"+a);
        System.out.println("val b;"+b);    

        }
}
class Constructordemo
{
public static void main(String []arg)
{
        Constructorover  s1=new Constructorover (10);
}
}
Save with an name of Constructordemo.java and run it..











Concept of This (this keyword)
Used to call the default constructor of the same class from the parameterized constructor of the same class.
This (…):- used to call the parameterized constructor of the same class from default constructor or other category constructor of the same class.
Whenever using the “this” keyword the statement must be the first statement must be the first statement. Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The keyword this is useful when you need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts.
class This1
{
int a,b;
 This1(){
this(50,60);
a=10;
b=20;
System.out.println("a="+a);
System.out.println("b="+b);
}
This1(int a,int b)
{

this(11);
this.a=a;
this.b=b;
System.out.println("aa="+a);
System.out.println("bb="+b);
}
This1(int a)
{
this.a=a;
b=a;
System.out.println("a1="+a);
System.out.println("b1="+b);
}

}
public class This
{
public static void main(String arg[])
{
This1 e=new This1();

}
}











Concept of super :-
It is the reserve keyword which is use to differentiate the base class feature with derive class features if and only if they are similar the base class feature will be practiced with super keyword
Super keyword plays an important role at three level
1. at variable level
2. at method level
3. at constructor level
At variable level:-
To access base class data member into derive class. If and only if the derive class data member’s and the base class data member are similar then the the base class data member keyword in the context of data member.
Ex.  Super base class data member;
At method level :-
To access the base class member method into derive class and derive class method and base class methods are similar than the base class methods will be called with respect to super keyword in the context of derive class.
At constructors level :-
Super() :-
 It is used to call the default constructors of the immediate base class from drive class.
Super(---) :-
 It is used to call the parameterized constructors of the base class from the drive class.
class Myclass
{
   public Myclass(int a,int b,int c)
        {
            System.out.println("\n"+a+"\n"+b+"\n"+c);
        }


}
class ourclass extends Myclass
{

        public ourclass(int l,int m,int n,int a,int b,int c)
        { super(a,b,c);
           System.out.println("\n"+l+"\n"+m+"\n"+n);
       
        }

}
class ownclass extends ourclass
{
       
        public ownclass(int x, int y,int z,int l,int m, int n,int a,int b,int c)
                {
        super(l,m,n,a,b,c);
                  System.out.println("\n"+x+"\n"+y+"\n"+z);
                        }
}
public class super1
{      public static void main(String args[])
        {
ownclass o=new ownclass(1,2,3,4,5,6,7,8,9);
}
}
Concept of Final(final keyword):-
Constants in java:-
Final :-
A variable level.
A method level.
A class level.

A construct is identified whose value is never be change during the vocation of program.
To declare a constant in java be have a result keyword known as final.
Final keyword plays an important role at the level of above.

Final variable declaration:-
                              Final float p;
In java final variable declaration is allow let her we can initialize value in to it only one time to the modification will not be possible.

Final variable declaration /initialization:-
No any modification is possible.
                                     final float pi=3.14t.
no together modification is allow.



Final at method level :-
class a                                                  class B extends A                                                      
{                                                                {
    Final void f1()                                          void f1()
    {                                                            {   
     ----------                                                                  ----------
     ----------                                                                  ----------
     }                                                           }
}                                                      }

One a method is declare final if can be reused multiple time but can not be redefined or variable.
Final class A                                            class B
{                                                                {
     Void f1()                                                  A 01=new A1();
      {                                                               {
       ---------                                                      ---------
       ---------                                                      ---------
       }                                                               }
}                                                                   }

Once a class is declare as final it can not be inherited directly.
Final variable value can not be changed.
Final method can not be redefined or overwrite.
Final class can not executed or inherited.
















Abstract Class:-
An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class.

abstract public class abstract-base-class-name {
// abstract class has at least one abstract method
public abstract return-type abstract-method-name ( formal-params );
... // other abstract methods, object methods, class methods
}
public class derived-class-name extends abstract-base-class-name {
public return-type abstract-method-name (formal-params) { stmt-list; }
... // other method implementations
}
It would be an error to try to instantiate an object of an abstract type:
abstract-class-name obj = new abstract-class-name(); // ERROR!
That is, operator new is invalid when applied to an abstract class.

Example:-
abstract class Abs
{
abstract public void f1();

}
class Abs1 extends Abs
{
public void f1()
{
System.out.println("we are in normal class");
System.out.println("F1 is printed");

}
}
class Abstractdemo{
public static void main(String arg[])
{
Abs1 o1=new Abs1();
o1.f1();

}
}


Interface:-
An abstract class mixes the idea of mutable data in the form of instance variables, non-abstract methods, and abstract methods. An abstract class with only static final instance variables and all abstract methods is called an interface. An interface is a specification, or contract, for a set of methods that a class that implements the interface must conform to in terms of the type signature of the methods. The class that implements the interface provides an implementation for each method,
just as with an abstract method in an abstract class.
So, you can think of an interface as an abstract class with all abstract methods. The interface itself  can have either public, package, private or protected access defined. All methods declared in an interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to declare a method in an interface to be abstract. You can define data in an interface, but it is less common to do so. If there are data fields defined in an interface, then they are implicitly defined to be:
• public.
• static, and
• final
In other words, any data defined in an interface are treated as public constants.
Note that a class and an interface in the same package cannot share the same name.




Example:-
interface I1
{
int a=5;
float f=3.2f;
void f1();
void f2();
}
class C1 implements I1
{
public void f1()
{
System.out.println("welcomre!!!.............in f1");
}
public void f2()
{
System.out.println("you are in f2");
}
}
class C2
{
Public static void main(String arg[])
{
C1 o1=new C1();
o1.f1();
o1.f2();
}
}






Inheritance:-
Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.
public class Animal{
}

public class Mammal extends Animal{
}

public class Reptile extends Animal{
}

public class Dog extends Mammal{
}
Now based on the above example, In Object Oriented terms following are true:
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are sub classes of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now if we consider the IS-A relationship we can say:
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence : Dog IS-A Animal as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.















Inheritance is a compile-time mechanism in Java that allows you to extend a class (called the base class or superclass) with another class (called the derived class or subclass). In Java,inheritance is used for two purposes:
1. class inheritance - create a new class as an extension of another class, primarily for the purpose of code reuse. That is, the derived class inherits the public methods and public data of the base class. Java only allows a class to have one immediate base class, i.e., single class inheritance.
2. interface inheritance - create a new class to implement the methods defined as part of an interface for the purpose of subtyping. That is a class that implements an interface “conforms to” (or is constrained by the type of) the interface. Java supports multiple interface inheritance.
In Java, these two kinds of inheritance are made distinct by using different language syntax. For class inheritance, Java uses the keyword extends and for interface inheritance Java uses the keyword implements.
public class derived-class-name extends base-class-name {
// derived class methods extend and possibly override
// those of the base class
}
public class class-name implements interface-name {
// class provides an implementation for the methods
// as specified by the interface
}



Example:-  (Simple Inheritance)
class Super
{
        int a,b;
        Super()
        {     
        a=11;
        b=22;
                System.out.println("val a;"+a);
        System.out.println("val b;"+b);    

        }
        Super(int a)
        {
        this.a=a;
        b=a;
                System.out.println("val a;"+a);
        System.out.println("val b;"+b);    

        }
}
class Super1 extends Super
{
        int a,b;
       
        Super1(){    
        a=111;
        b=222;
        System.out.println("val a;"+a);
        System.out.println("val b;"+b);    
}
        Super1(int a)
        {
        this.a=a;
        b=a;
                System.out.println("val a;"+a);
        System.out.println("val b;"+b);    

        }
        void add(int a)
        {
        int c=super.a+a;
        System.out.println("sum of superclass var and derivedc var="+c);
       
        }
}
class Sadd
{
public static void main(String []arg)
{
        Super1 s1=new Super1(4);
        s1.add(4);
}
}








Inheritance with interface:-
interface i1
{
int a=5;
float f=3.2f;
void f1();
void f2();
}
interface i2
{
int a=5;
float f=3.2f;
void f3();
void f4();
}
interface i3 extends i1,i2
{
}
class c1 implements i3
{
public void f1()
{
System.out.println("in f1");
}

public void f2()
{
System.out.println("in f2");
}


public void f3()
{
System.out.println("in f3");
}

public void f4()
{
System.out.println("in f4");
}
}
class Interfacedemo
{
public static void main(String sa[])
{
c1 c=new c1();
c.f1();
c.f2();
c.f3();
c.f4();
}
}










Static Methods:-
A static method can be accessed without creating an instance of the class. If you try to use a non-static method and variable defined in this class then the compiler will say that non-static variable or method cannot be referenced from a static context. Static method can call only other static methods and  static variables defined in the class. Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class.










Example:-
class demo
{
                public  void nonstatic()
                {
                        System.out.println("non static function");
                 }
public static void s()
{
  System.out.println("static function");
  demo o=new demo();
   o.nonstatic();
}
}



class staticcallbyinstance
{
        public static void main(String arg[])
        {//         demo o=new demo();
              demo.s();        // instance is not required for the static class
        }

}


Static block in java:-
In java you see "static variables", "static methods", "static classes" and "static blocks". Static variables, static methods and static classes are known to everyone but what is this "static block". Lets see what, where and how these static blocks are used. You cannot declare a top-level class as a static class. Java will throw a compilation error. Only inner classes that are member classes can be declared as static. If we declare member classes as static, we can use it as a top-level class outside the context of top-level class.
Static blocks are also called Static initialization blocks . A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
    // whatever code is needed for initialization goes here
}
Static block is excuted before the main method of any class means the static block is excuted first.







Example:-
class staticblockdemo
{
public static void main(String args[]) {
                System.out.println("main() is executing");
        }
static{
System.out.println("static{} is executing");
        }

}
Here the static block is excuting first















Overloading of main() function:-
In java there is an facility to overload the main method like normal method overloading .Here is the code to overload the main method in java .
Example:-
class mainmethodoverloadingdemo
{
                public static void main(String arg[])
                {
                        System.out.println("main(String) is executing");
                        for(int i=0;i<arg.length;i++)
                        {
                                System.out.print("value of args["+i+"]"+arg[i]);
                        }}
                public static void main(byte arg[])
                {
                        System.out.println("main(byte) is executing");
                        for(int i=0;i<arg.length;i++)
                        {
                                System.out.print("value of args["+i+"]"+arg[i]);
                }      }
        public static void main(short arg[])
                {
                   System.out.println("main(Short) is executing");
                        for(int i=0;i<arg.length;i++)
                        {
                                System.out.print("value of args["+i+"]"+arg[i]);
                }      }
public static void main(int arg[])
                {
                   System.out.println("main(int) is executing");
                        for(int i=0;i<arg.length;i++)
                        {
                                System.out.print("value of args["+i+"]"+arg[i]);
                }      }
        public static void main(float arg[])
                {
                        System.out.println("main(float) is executing");
                        for(int i=0;i<arg.length;i++)
                        {
                                System.out.print("value of args["+i+"]"+arg[i]);
                        }             
                }
                public static void main(int a,float b,int c)
                {
                        System.out.println("main(different) is executing");
                        System.out.println(+a);
                        System.out.println(+b);
                        System.out.println(+c);
                }

static
{

System.out.print("static{} is executing");
byte bytearr[]={0,1,2,3,4,5};
short shortarr[]={0,1,2,3,4};
int intarr[]={0,1,2,3};
float floatarr[]={0.1f,1.4f,2.5f};
String argarr[]={"madhuri","nemade"};
main(bytearr);
main(argarr);
main(shortarr);
main(intarr);
main(floatarr);
main(10,20.8f,3);
System.out.print("static blok is over");

}
}
After over the static block the String main is start excuting.




















Factory Method:-
An object for abstract class can be created in two ways.
By creating an object of that concretes derive class which is extending this abstract class.
By using the concept of factory method.
A factory method is one which is used to create an object of a class without using new operator.
Rules for  use factory method.
(a)The return type of the factory method must be that class type in which it is present.
(b)Every Factory method must be static.
(c)Every factory method must be public.













Example:-
import java.awt.GraphicsEnviroment;
class Factory
{
public static void main(String []args) throws Exceptions
{
GraphicsEnviroment ge = GraphicsEnviroment.getLocalGraphicsEnvoirment();
String font[]=ge.getAvailableFontFamilyNames();
System.out.println("Total no of fonts:"+font.length);
for(int e=0; e<font.length; e++)
{
System.out.println("font name:"+font[e]);
}     
}
}





















Classloader :-
Classes are introduced into the Java environment when they are referenced by name in a class that is already running. There is a bit of magic that goes on to get the first class running (which is why you have to declare the main() method as static, taking a string array as an argument), but once that class is running, future attempts at loading classes are done by the class loader.
At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name. The method definition is:
Class r = loadClass(String className, boolean resolveIt);

The variable className contains a string that is understood by the class loader and is used to uniquely identify a class implementation.









Example:-
class classloaderdemo
{
   public static void main(String arg[]) throws Exception
        {
                Class c=Class.forName("classloaderdemo");    
                ClassLoader c1=c.getClassLoader();
        java.security.ProtectionDomain pd=c.getProtectionDomain();
        System.out.println("class Loader Name :"+c1);
        System.out.println("-----------------------");
        System.out.println("ProtectionDomain Name :"+pd);
                System.out.println("-------------------------");

                }
}