Java

Introduction to Java


Java was developed by James Gosling at Sun Microsystem Inc.
Introduction to Java :-
-Java was developed by James Gosling at Sun microsystem Inc.
-Firstly java language called by name Oak.
-But Oak is registered by another things.
-So it is introduced java.
-Sun microsystem company made in 1991.
-It is made by 4 person in which one is vinod khosler , whose co-founder of sun microsystem.
-Java language is platform independent language.
-Java is ideal language because java has many features in which features of web application , so that java is hit in instantly.
-On January 27 , 2010 Sun was acquired by Oracle Corporation for US$7.4 billion.
-Java Is Everywhere :-


-Java resides in mobiles , client machines , server machines , embedded devices, smart phones , cloud etc.
-It shares the same basic features of the language and libraries.
Principle of Java :-
-Write Once , Run Anywhere (WORA).
What Is Library :-
-Java library is a collection of predefined classes.
-You can use these classes either by inheriting them or by instantiating them.
Java Flavours :-
1)Java SE (Core Java) – Standard Edition .
2)Java EE (Advance Java) – Enterprice Edition (for Web Application Server Application).
3)Java ME (Micro Edition for Mobiles).
4)Many More…




Features of Java :-
-Simple – Java is simple language , easy to learn.
-Object Oriented Language.
-Distributed. (Applet , RMI , etc.)
-Interpreted language. (Java has a compiler , but it`s purpose is different to c and c++)
-Robust. (for every situation , java has response or solution)
-Secure.
-Portable. (platform independent)
-Multi-Threaded.
-Garbage Collector.
-Java is a case-sensitive language like c and c++.
-Java is nearly 100% object oriented language.
-In java , it is not possible to make a function which is not a member of any class. (as we can do in c++)
First Program In JAVA
Public class HelloWorld
{  public static void main(String []args)
  System.out.println(“Hello World”);
  }
}
-Outer class is only public or default.
-But inner class is become , private , protected , public , default.
-Class is a concept of encapsulation.
-Here data type is HelloWorld.
-Class name is written in Cammel-Notation in java language.
-In java , main() function is also a member function.
-Static member is of class member.
-Non-Static member is of Instance (object) member.
-Static member (function) does not depend on object for calling purpose.
-(String []args) is a prototype.
-Here String is a name of class means data type.
-So that we can make variables of this.
-Here we can make variables of array is args , in which we will store the many strings.
-System.out.println
-System is a class and after this here is a dot(.) which is represent that we access static members of class.
-out is assume as static onject/object reference.
-Which call the our member function . Here member function is println.
-println automatically change the line.
Data Types
-Data type is defined for handle the data.
-A type identifies a set of values (and their representation in memory) and a set of operations that transform these values into other values of that set.
-Java is strongly type language.
Types :-
1)Primitive types. (Predefined or built in data type)
2)User defined types.
Primitive data types :-
-Boolean
-Char
-Byte
-Short
-Int
-Long
-Float
-Double
Variables :-
-int counter ; (handle for only ordinary data)
-double temp ; (handle for only ordinary data)
-String name ; (Object oriented philosphy)
-int[] ages ; (Not primitive)
-char letters[] ; (for array)
Constants :-
-Integer constant consists of a sequence of digit.
-If the constant is to represent a long integer value , it must be suffixed with am uppercase L or lowercase l.
-If there is no suffix the constant representation 32 bit integer (An int).
-Integer constant can be specified in the decimal , hexadecimal , octal or binary digit.
Type Conversion In JAVA
Comments :-
1)Block Style Comments begin with /* and terminate with */ that spans multiple lines.
2)Line Style Comments begin with // and terminate at the end of the line.
3)Documentation Style Comments begin with /** and terminate with */ that spans.
4)Multiple Lines . They are generally created using the automatic documentation tool such as java.
Conversion :-
-Every exception written in java programming language has  a type that can be deduced from the structure of the expression and the types of the literals , variables and methods mentioned in the expression.
Widening Conversion :-
-int y=3;
-float x=y; //widening conversion , no error
Narrowing Conversion :-
-float x=3.4f ;
-int y=x ; //narrowing conversion , error
-int y=int(x) ; //no error (type casting)
-float k=3.5 ; //narrowing conversion , error
-float k=3.5f ; //no error
Permitted Conversion :-
1)Byte to short , int , long , float , or double.
2)Short to int , long , float , or double.
3)Char to int , long , float , or double.
4)Int to long , float , or double.
5)Long to float or double.
6)Float to double.
Classes & Objects In JAVA
Why Class ?
-Primitive data types (Variables grouping)
-Non Primitive data types
-> Object oriented philosophy is that one entity related information should be keep in one place.
-> For this we make classes.
-> So that we need a data types in which we can store many type information.
Class :-
-Class is a description of an objects property and behaviour.
-Creating class is as good as creating data type.
-Class is defining a category of data.
Objects :-
-Objects is a real world entity.
-Objects is an instance of a class.
-Objects construct memory to hold property values.
-Objects is a memory block. 







Package In Java :-



  • Packages are nothing more than the way we organize files into different directories according to their functionality , usability as well as category they should belong to.
  • Files in one directory or package would have different functionality from those of another directory.
Eg :- Files in java.io package do something related to I/O but files in java.net package give us the way to deal with the network.

Name Collision :- 

  • Packaging also help us to avoid class name collision when we use the same class name as that of others.
  • The benefits of using package reflects the ease of maintainance , organization and increase collaboration among developers.
How to create Package :-
  • Suppose we have a file called Helloworld.java , and we want to put this file in a package world.
package world;
public class HelloWorld {
       public static void main(String[] args)
       {
            System.out.println("Hello World");
       }
}

Remember :-
  • We can have only one public class in a single java file.
  • Name of the file should be same as the name of public class.
  • In absence of public class , any class name can be given to the file name.

Use of import In Java :-
  • import is a keyword in java.
  • It is used to import classes of other packages

package pack2;
public class Student{
    private int rollno;
    private String name;
    public void setRollno(int r){
        rollno=r;
   }
    public void setName(String n){
        name = n;
   }
    public int getRollno(){
       return(rollno);
   }
    public string getName(){
       return(name);
    }
}


======

package pack1;
import pack2.Student;

public class Example{
       public static void main(String [] args){
             Student s1 = new Student();
             s1.setRollno(100);
             s1.setName("manu");
     System.out.println("Rollno" + s1.getRollno());
     System.out.println("Name" + s1.getName());
      }


Access Modifiers In Java :-
1) Java Support four categories of accessibility Rules .
     - Private
     - Protected
     - Public 
     - Default
2) Modifiers can be used for class , members , variables , and member functions

With Class :-
1) Outer class and inner class.
2) for outer class , there can be only two possibilities either class is a public class or just a class which means it is of default type.
3) For inner class any among four access modifiers can be use.
       
Member Variable and Functions :-
1) When members of the class are private , they can not accessed from outside the class body. They are meant to be accessed from the same class in which they are declared.
2) When members are protected , they can be accessed from any class of the same package and child class from other package.
3) When members are public they are accessible from any class of any package.
4) When members are default they are accessible only from the class of same package.


Constructor In Java :-
- Constructor is a member function of a class .
- The name of the constructor is same as the name of the class.
- Constructor has no returns type.
- Constructor is special member function.

public class Box{
      private int l,b,h;
      public Box() {
          l=10;
          b=8;
          h=4;
     }
      public static void main(String[] args)
      {
           Box b1 = new Box();
      }
}



Constructor Overloading :-
- Constructor overloading means more than one constructor become in one class.
- A constructor is a special method that is used to initialize a newly created object and is called implicitly just after the memory is allocated for the object.
- It is not mandatory for the coder to write a constructor for the class.
- When there is no constructor defined in a class by programmer compiler implicitly provide a default constructor for the class.


- Constructor can be parameterized
- Constructor can be overloaded.




Inheritance In Java :-
- Inheritance is a key concepts of oops.

Syntax :-
class subclass extends superclass
{}

- extends is a keyword
- base class means superclass/Parentclass
- Derived class means subclass/childclass.


person.java
public class person{
    private int age;
    private String name;
    public void setAge(int a ){
          age = a;
   }
   public void setName(String n){
          name = n;
  }
   public int getAge(){
         return(age);
    }
   public String getName(){
          return(name);
     }
}


student.java
class student extends person {
       private int rollno;
       public void setRollno(int r){
             rollno = r;
       }
      public int getRollno(){
             return(rollno);
       }
}



Example.java
public class Example{
              public static void main(String[] args){
                  Student s1 = new Student();
                    s1.setRollno(100);
                    s1.setName("manu");
                              s1.setAge(20);
                    System.out.println("Rollno" + s1.getRollno());
                    System.out.println("Name" + s1.getName());
                    System.out.println("Age" + s1.getAge());
          } 
}



Java Support :-
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance



Initialization block or Initializer :-
There are two types of initialization blocks
- Instance initialization block
- Static initialization block

1) Instance Initialization Block :-
public class Test {
      private int x;
      {
            System.out.println("initialization block =" +x);
             x = 5;
      }
      public Test() {
             System.out.println("Constructor : x = " +x);
      }
      public static void main(String [] args) {
             Test t1 = new Test();
             Test t2 = new Test();
      }

}


2) Static Initialization Block :-
public class Test {
      private static int x;
      static {
          System.out.println("static initialization block : k = " +k);
          k = 10;
     }
      public static void main(String [] args) {
            new Test();
      }
}

Overloading and Overriding in Java :-

1) Function Overloading in Java :-
- If two methods of a class (whether both declared in the same class , or both inherited by a class or one declared and one inherited) have the same name but signatures that are not same then the method name is said to be overload.
- Method overloading is a way to implement polymorphism.

2) Overriding in Java :-
- Method overriding is defining method in subclass with the same signature with specific implementation in respect to the subclass.

- Why Overriding ?

Final Keyword In Java :-

  1. final instance variable 
  2. final static variable
  3. final local variable
  4. final class
  5. final methods
1) Final Instance Variable :-  A java variable can be declared using the keyword final. Then the final variable can be assigned only once.
         A variable that is declared as final and not initialized is called a blank final variable. A blank final variable forces either the constructor to initialize it or initialization block to do this job.

Eg- public class Example {
            private int x; // Instance member variable.
}

Eg- public class Example {
            private final int x; // final Instance member variable.
}


2) Final Static Variable :-  static member variable when qualified with final keyword , it becomes blank until initialized.

       final static variable can be initialized during declaration or within the static block.

Eg- public class Example {
               private final static int y; // final static member variable.
}


4) Final Class :-  java classes declared as final cannot be extended , and restricting inheritance.

Eg-  final class Dummy {}
           class MoreDummy extends Dummy //XXXXXX Wrong


5) Final Methods :-  Methods declared as final cannot be overriden.


this Keyword In Java :- 
  1. this object reference is a local variable in instance member methods referring to the caller object.
  2. this keyword is used as a reference to the current object which is an instance of the current class.
  3. this reference to the current object is useful in which situations where a local variable hides, or shadows a field with the same name.

Eg-  public class Example {
              private int l,b,h;
              public void setDimensions(int l, int b, int h) {
                         this.l =l;
                         this.b =b;
                         this.h =h;
             }
}


- If a method needs to pass the current object to another method, it can do so using the this reference.
- Note that the this reference cannot be used in a static context, as static code is not executed in the context of any object.



super Keyword In Java :-
  1. In inheritance, subclass object when call an instance member function of subclass only, function contain implicit reference variable this and super both referring to the current object (object of subclass).
  2. The only difference in this and super is 
             - this reference variable is of subclass type.          - super reference variable is of superclass type.


Use of super Keyword :-       

  1. If your method overrides one of its super class method, you can invoke the super class  version of the method, through the use of the keyword super.
  2. It avoids name conflict between member variables of superclass and subclass. 



Constructor Chaining In Java :-
  1. Constructor can call constructor of the same class or super class.
  2. Constructor call from a constructor must be the first step (call should appear in the first line).
  3. Such series of invocation of constructors is known as constructor chaining.
Eg- class A {
          public A() {
               System.out.println("A");
          }
       }
       class B extends A{
           public B() {
                System.out.println("B");
       }   
     }
     public class Example {
         public static void main(String []args){
                       B obj = new B();
      }
   }


super() or this() :-  

  1. first line of constructor is either super() or this() .....by default super().
  2. Constructor never contains super() and this() both.
Eg- class A {
          public A() {
              System.out.println("A");
        }
      }
     class B extends A {
          public B() {
              this(4);
              System.out.println("B1");
          }
         public B(int k){
              System.out.println("B2");
         }
     }
     public class Example {
         public static void main(String []args){
               B obj = new B();
         }
     }

Abstract Class In Java :- 

  1. Abstract classes are declared with the abstract keyword.
  2. An abstract class cannot be instantiated.
  3. Abstract class has no object.
Eg- abstract class Person {
           private String name ;
           private int age ;
            
           public void setName(String n) {
                 name = n;
           }
          public void setAge(int a) {
                 age = a;
           }
      }
      class abstract Example {
           public static void main(String []args) {
                   Person p = new Person() ;
           }
      }




Why Abstract Class ??

  1. Java abstract classes are used to declare common characteristics of sub-classes.
  2. It can only be used as a super class for other classes that extend the abstract class.
  3. Like any other class, an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform.
  4. You can not create object of abstract class but you can create reference variable of abstract class.
Eg- abstract class A{ }
       class B extends A { }
       public class Example {       
            public static void main(String []args) {
                    A o1 = new B();
            }
       }

Abstract Methods In Java :- 
  1. An abstract class can include methods that contain no implementation. These are called abstract methods. The abstract method declarations must then end with a semicolon rather than a block.
  2. If a class has any abstract methods, whether declared or inherited, the entire class must be declared abstract.
What is wrong with this code below ??

class Person {
  ........
  abstract void show();
}
class Student extends Person {
  ........
}
class Abstract Example {
     public static void main(String []args) {
            Student s = new Student();
    }
}


Right Code is Below --

abstract class Person {
   ......
   abstract void show();
}
class Student extends Person {
   ....
   void show() {}
}
public class abstract Example {
        public static void main(String []args){
                 Student s = new Student();
                  s.show();
        }
}


Interface In Java :-

  1. Interface definition begin with a keyword interface.
interface SomeName {}

  • Interface just specify the method declaration, (implicitly public and abstract) and can only contain fields (which are implicitly public, static, final).
interface SomeName {
       int x;
       void someFunction();
}

  • Interface all members variables and methods are by default public.
- Implementing Interface

interface I1 {
    void someFunction();
}
class A implements I1 {
    public void someFunction() {
              //Some code
   }
}

  • Interface only provide prototype of functions not provides function definition or implementations.
  1. An interface like that abstract class cannot be instantiated.
  2. Interface do not have constructors.
  3. If  a class that implements an interface ,does not define all the methods of the interface, then it must be declared abstract and the method definitions should be provided by the subclass that extends the abstract class.
Extending & Implementing :-
   - Multiple extension is allowed when extending interface i.e one interface can extend none, one or more interfaces.

Object Reference :-
  • You can not create object of any interface but creation of object reference is possible.
  • Object reference of interface can refer to any its subclass type.  
Eg - interface I1 {
         void f1();
       }
       interface I2 {
         void f2();
      }
      class A implements I1, I2 {
          public void f1() {
               System.out.println("I1");
          }
          public void f2() {
              System.out.println("I2");
          }
         public void f3() {
               System.out.println("a");
         }
      }
      public class Example {
           public static void main(String []args) {
                    A obj = new A() ;
                         obj.f1();
                         obj.f2();
                         obj.f3();
           }
      }


Introduction to Exception Handling In Java :-

What Is Exception ?? -
  • Exception in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime.
Four Options :-
  1. Default throw and default catch
  2. Default throw and our catch
  3. Our throw and default catch
  4. Our throw and our catch






































































Comments

Post a Comment

Popular posts from this blog

C++ Language

C Language

Java Language