Tutorial

JAVA DOT NET  SQL 



JAVA TUTORIAL   

Topics:

      1.   Java Definition
            2.  Tokens
      3    Variables
      4.  Data Types
      5    Methods
      6.   Arrays
      7.   Class and Object
      8.   Interface and Abstract  class
      9.   Oops concept
    10.    Inheritance
    11.   Polymorphism
    12.   Encapsulation
    13.   Abstraction
    14.   Exception Handling
    15.   Multithreading
    16.   GUI
    17.   File Handling
    18.   JDBC
    19. Collections


  1. JAVA DEFINITION
J     
 Java is a programming language expressly designed for use in the distributed environment of the Internet. It    was designed to have the "look and feel" of the C++ language, but it is simpler to use than C++ and  enforces an object-oriented programming model.
J   
  Java is platform independent(WRITE ONES AND RUN  ANY WHERE)

   2. TOKENS

      Java tokens are the smallest individual units of a Java Program that is meaningful to the compiler. Different types of java tokens are:
  • Reserved Keywords – Reserved keywords are java tokens with predefined meaning. Java has 60 reserved keywords.
  • Identifiers – Identifiers are java tokens designed and decided by the java programmer. Examples for java tokens namely identifiers are: name for the class, name for members of the class, and temporary variables in class methods.
  • Literals – Literals are java tokens containing set of characters. Literals are used to represent a constant that has to be stored in a variable.
  • Operators – Operators are java tokens containing a special symbol and predefined meaning in Java. Operators can be used with one or more operands to achieve a result.
  • Separators – Separators are java tokens that are used to divide as well as arrange codes in group.
3. VARIABLES

   A variable is something that can store data, such as numbers and words. A variable has some size    and type.
 for example : int i = 10; Here "i" is a variable .    
         
    4. DATA TYPES

        In Java, every variable has a type declared in the source code. There are two kinds of types:    a).reference types 
       b). primitive types.

        Reference types are references to objects. Primitive types directly contain values. There are 8    primitive types:
  • byte
  • short
  • int
  • long
  • char
  • float
  • double
  • boolean
 5. METHODS

   Method is the like the behaviour means how it behaves at run time. It is the set of instruction to solve    a problem.

   A method definition consists of a method header and a method body. Here are all the parts of a method:
  • Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.
  • Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.
  • Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.
  • Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method Body: The method body contains a collection of statements that define what the method does.
t

4       6. ARRAYS

           Array is the collection of similar data type.An array, in the context of Java, is a dynamically-created    object that serves as a container to hold constant number of values of the same type. By declaring an  array, memory space is allocated for values of a particular type. At the time of creation, the length of  the array must be specified and remains constant.


        7. CLASS AND OBJECT

          Class : A class is blueprint for an object. It is the description that tells the Java Virtual Machine how to     make an object of partucarlar type.

          Object : Object is the instance of a class. It has two things : one is states and another is behaviour.
          States are the things that object knows and behaviour is the responsibility that object has to do.

          States -instance variables
         Behaviour -Methods

     8. INTERFACE AND ABSTRACT CLASS


              A)  Interface:          An interface in Java is similar to a class, but the body of an interface can include only abstract methods and final    fields (constants). A class implements an interface by providing code for each method declared by the interface.
     
         Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must    implement all of the methods described in the interface, or be an abstract class.

           Interfaces are used to encode similarities which the classes of various types share, but do not necessarily constitute a class relationship. 

            B) Abstract Class :
            An abstract class is a class that is declared abstract—it may or may not include abstract methods.    Abstract classes cannot be instantiated, but they can be subclassed.  

           Unlike interfaces, abstract classes can contain fields that are not static and final, and they can    contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a  partial implementation, leaving it to subclasses to complete the implementation.

        9. OOPS CONCEPT

         Object Oriented Programming or OOP is the technique to create programs based on the real world. In the    OOP programming model programs are organized around objects and data.
         Four fundamental OOP concept :
         a. Inheritance : It is the property by which one class inherits the property of another class.
         b. Polymorphism : It is the property of an object to acquire more than one form.
         c. Encapsulation : Binding up of data and code together to form a single unit is encapsulation.
        d. Abstraction : Abstraction is the process of hiding the details and exposing only the essential features of a particular concept or object. 
           
         10. INHERITANCE : Inheritance is defined as the process where one object acquires the properties of another.Using inheritance, we create "IS-A" relationship. for example : parrot "IS - A" bird.
                A class derived from another class is called a subclass, whereas the class from which a subclass is derived is called a superclass.
               TYPES OF INHERITANCE : 
         a) Single Inheritance : A Scenario where one class is inheriting/extending the behavior of just one      super class.
b       b) Multilevel Inheritance : A Scenario where one class is inheriting/extending the behavior of another class which in turn is inheriting behavior from another class. 
         c) Hierarichal Inheritance : A Schenario where many sub class inheriting the behaviour of one parent class and form a tree like structure.
         d) Hybrid Inheritance : Combination of any two or more types of inheritance is Hybrid Inheritance.

       11. POLYMORPHISM :  is the ability of an object to take on many forms.Any Java object that can pass more than one        IS-A test is considered to be polymorphic.
             TYPES OF POLYMORPHISM : 
             a). Compile Time Polymorphism(Static Binding)
             b). Run Time Polymorphism(Dynamic Binding)

         Compile Time Polymorphism : Binding of data and code at compile time.
         Example : Method Overloading

         Run Time Polymorphism : Binding of data and code at run time.
         Example : Method Overriding 

             12. ENCAPSULATION : Binding of data and code into a single unit.Encapsulation is the technique of  making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it  cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
           
           Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class.
          The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code.

                 13. ABSTRACTION : Abstraction simplifies the complexity by modeling classes appropriate to the problem, and working at the most appropriate level of inheritance for a given aspect of the problem. 
           Abstraction means looking for the common or general features of something and without which the object is called by that name.
For example, if you consider Car: It should have 4 wheels, a steering wheel, an engine and a body. Without which any object is not called a Car(ideally!).

    14. EXCEPTION HANDLING : An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:
  • A user has entered invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.,e.t.c.
    TYPES OF EXCEPTION :
    a) Checked Exception : A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.
    b) Run Time Exception : A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.
    Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. 
    DIFFERENCE BETWEEN CHECKED AND UNCHECKED EXCEPTION
    1.Checked exception is to be handled at compile time while Unchecked exception doesn't.
    2.Checked exception represents scnerio with higher failure rate while Unchecked exception is mainly due to programming error.


    15. MULTHREADING : A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.

    Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum.

    Life Cycle of a Thread:

    A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. Following diagram shows complete life cycle of a thread.
    Java Thread
    Above-mentioned stages are explained here:
    • New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
    • Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
    • Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task.A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.


    • Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
    • Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

    17. JDBC : is a Java API that is used to connect and execute query to the database.JDBC API uses jdbc driver to connect to the database.

    WHY USE JDBC : Before JDBC, ODBC is used to connect and execute query to the database. But ODBC API uses ODBC driver that is written in "C" language which is platform dependent and unsecured.That is why Sun Microsystem has defined its own API(JDBC API) that uses JDBC driver written in Java language.

    JDBC Architecture




    Java application calls the JDBC library. JDBC loads a driver which talks to the database
    In general, to process any SQL statement with JDBC, you follow these steps:

    a)      Register the driver class
    b)       Creating connection
    c)        Creating statement
    d)        Executing queries
    e)   Closing connection

    Step 1: Register the driver class

    To load the driver, you need to load the appropriate class, make a driver instance and register it with the JDBC driver manager.
     Use Class.forName(String) method. This method takes a string representing a fully qualified class name and loads the corresponding class. Here is an example:
     
    try {
        Class.forName("connect.microsoft.MicrosoftDriver");
        //Class.forName("oracle.jdbc.driver.OracleDriver"); for Oracle driver
        //Class.forName("com.sybase.jdbc.SybDriver"); for sybase driver
    } catch(ClassNotFoundException e) {
        System.err.println("Error loading driver: " + e);
    }
    


    Step 2: Create The Connection Object

    To make the actual network connection, pass the URL, the database username, and the password to the getConnection method of the DriverManager class, as illustrated in the following example.
     
     String username = "jay_debesee";
     String password = "secret";
     Connection connection =
            DriverManager.getConnection(oracleURL, username, password);
    
    Other useful methods in the Connection class include
    • prepareStatement
    • prepareCall
    • rollback
    • commit
    • close
    • isClosed

    Step 3: Create a Statement Object

    A Statement object is used to send queries and commands to the database and is created from the Connection as follows:
     
    Statement statement = connection.createStatement();

    Step 4: Execute a Query or update

    Once you have a Statement object, you can use it to send SQL queries by using the executeQuery method, which returns an object of type ResultSet. Here is an example:
     
    String query = "SELECT col1, col2, col3 FROM sometable";
    ResultSet resultSet = statement.executeQuery(query);
    
    To modify the database, use executeUpdate instead of executeQuery, and supply a string that uses UPDATE, INSERT, or DELETE.

    Step 7: Close the Connection

    To close the connection explicitly, you should do:
     
    connection.close();
    



    18. COLLECTIONS
    Collection represents the group of objects. Depending on the method of storing and retrieving, collections are basically divided into three parts – 
    1). List(Interface) :  List can have a duplicate values stored in it sequentially
       a). ArrayList :The ArrayList class extends AbstractList and implements the List interface. ArrayList supports    dynamic arrays that can grow as needed.
       b). LinkedList : The LinkedList class extends AbstractSequentialList and implements the List interface. It provides a linked-list data structure.
       c).Vector Vector’s methods are synchronized and ArrayList’s methods are not synchronized.
    2).Set(Interface) : Set does not contain duplicate values.
    The Java platform contains three general-purpose Set implementations:
    a).  HashSet : stores its elements in a hash table, is the best-performing implementation; however it makes no guarantees concerning the order of iteration.
    b).  TreeSet : stores its elements in a red-black tree, orders its elements based on their values; it is substantially slower than HashSet.
    c).  LinkedHashSet : it is implemented as a hash table with a linked list running through it, orders its elements based on the order in which they were inserted into the set (insertion-order).

    3). Map(Interface) : Map contains key value type of data. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.
    The Java platform contains three general-purpose Map implementations:
    a). HashMap :HashMap is implemented as a hash table, and there is no ordering on keys or values. 
    b). TreeMap :TreeMap is implemented based on red-black tree structure, and it is ordered by the key.
    c).  LinkedHashMap :LinkedHashMap preserves the insertion order.It is the sub class of HashMap.

     Collection framework is provided in “java.util” package. Collection is the parent interface of all collections in java.
    LIST:
     The List interface extends Collection and declares the behavior of a collection that stores a sequence of elements.

    • Elements can be inserted or accessed by their position in the list, using a zero-based index.
    • A list may contain duplicate elements.
    • In addition to the methods defined by Collection, List defines some of its own.These are:void add(int index, Object obj), boolean addAll(int index, Collection c),Object get(int index) and many more.
    • Several of the list methods will throw an UnsupportedOperationException if the collection cannot be modified, and a ClassCastException is generated when one object is incompatible with another.
    SET:
    A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
    The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited.

    Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
    MAP:
    The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date.
    • Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
    • Several methods throw a NoSuchElementException when no items exist in the invoking map.
    • A ClassCastException is thrown when an object is incompatible with the elements in a map.
    • A ClassCastException is thrown when an object is incompatible with the elements in a map.
    • A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map.
    • An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map.
    The Java Collections Framework provides the following benefits:

    • Reduces programming effort: By providing useful data structures and algorithms, the Collections Framework frees you to concentrate on the important parts of your program rather than on the low-level "plumbing" required to make it work. 
    • Increases program speed and quality: This Collections Framework provides high-performance, high-quality implementations of useful data structures and algorithms. The various implementations of each interface are interchangeable, so programs can be easily tuned by switching collection implementations. Because you're freed from the drudgery of writing your own data structures, you'll have more time to devote to improving programs' quality and performance.
    • Reduces effort to learn and to use new APIs: Many APIs naturally take collections on input and furnish them as output. In the past, each such API had a small sub-API devoted to manipulating its collections. There was little consistency among these ad hoc collections sub-APIs, so you had to learn each one from scratch, and it was easy to make mistakes when using them. With the advent of standard collection interfaces, the problem went away.
    • Reduces effort to design new APIs: This is the flip side of the previous advantage. Designers and implementers don't have to reinvent the wheel each time they create an API that relies on collections; instead, they can use standard collection interfaces.

No comments:

Post a Comment