Saturday, 24 December 2016

wait() and notify() methods in Java

Wait():-
            It is a method of class Object which is used to suspend a thread in monitor.
public void wait() throws InterruptedException;

Notify():-
            It is also a method of class Object which is used to resume a thread which has suspended in monitor.

public void notify();

Synchronization In Java

Ex :
            synchronized(threadobj)
            {        
                        threadobj.start();
            }

            * A method wants to allow only one thread at a time to execute,
then that should be declared as synchronized method or that should be called within synchronized block.
            * When a thread enters into synchronized method, it is locked and monitored.
Meanwhile, other threads are waiting for sometime until it terminates.
            * It is used to achieve InterThread Communication.
 (Output of one thread is used as input by another thread.)

            * It is used to avoid DeadLock prone.

Thread - Functions

Thread
            It is class of java.lang package to create a new thread.
constructors:-
Thread();
Thread(String threadname);
Thread(Runnable);
Thread(Runnable,String threadname);
Methods:-
public void start()  (Start a thread by calling its run method.)
     Causes this thread to begin execution; the JVM calls the run method of this thread.



public void run()  (Entry point for the thread)
            statements with in this method will be executed more than one threads
concurrently.
public void join() throws InterruptedException
            waits for a thread to terminate.
public static int activeCount()
          Returns the current number of active threads in thread group.
public void stop()     
public void suspend()           
public void resume()
public static Thread currentThread()     
public static void sleep(long ms) throws InterruptedException;
            Suspend a thread for a period of time.
public String getName();
            Obtain a thread’s name.
public void setName(String);
            set Thread’s Name.
public boolean isAlive();
            Determine if a thread is still running.
public void setPriority(int);
            Set a thread’s priority.like
   Thread.MIN_PRIORITY              -           1
   Thread.NORM_PRIORITY           -           5

   Thread.MAX_PRIORITY             -           10

There are two ways to create a new thread of execution

ü    1. One is to declare a class to be a subclass of "Thread".This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started.
ü    2. The other way to create a thread is to declare a class that implements the is "Runnable" interface. That class then implements the run method. An instance of  the class can then be allocated, passed as an argument when creating Thread, and started.

Multi Threading

A thread is a thread of execution in a program. We can execute more than one threads concurrently to utilize the cpu efficiently.
            The JVM allows an application to have multiple threads of execution running concurrently.
            When a JVM starts up, there is usually a single thread (which typically calls the method named main of some designated class).

Thursday, 8 December 2016

Java - Sample Program

class Sample
{
public static void main(String s[])
{
System.out.println("welcome");
}
}

Java - PrintWriter

PrintWriter
        It is used to write any type of data to byte-oriented o/p stream as well as char-oriented o/p stream.
        When we use constructors and methods of this class, no need to throw IOException.
        We should set flush state as true.
constructors:-
PrintWriter(OutputStream);
PrintWriter(OutputStream,boolean flushstate);
PrintWriter(Writer);
PrintWriter(Writer,boolean flushstate);
methods:-
public void print(int);     //(for all data types)
public void print(String);
public void print(Object);
public void println(int);  //(for all data types)
public void println(String);

public void println(Object);

Java - BufferedReader and BufferedWriter and InputStreamReader

BufferedWriter
        It is used to write data to particular o/p stream and to avoid system call(OS) occurence for every process.
constructor:-
BufferedWriter(Writer);
methods:-
public void newLine();
BufferedReader
        It is used to read data from particular i/p stream and to avoid system call(OS) occurence for every process.
constructor:-
BufferedReader(Reader);
method:-
public String readLine();

InputStreamReader
        It acts as bridge between byte-oriented and char-oriented streams.
constructor:-

InputStreamReader(InputStream);

java - FileWriter and FileReader

FileWriter
        To write data to particular file.
constructors:-
FileWriter(String filepath&name);
FileWriter(String path&name,boolean append);
FileWriter(File);
methods:-
        Same as it's base class.

FileReader
        To read data from particular file.
constructors:-
FileReader(String filepath&name);
FileReader(File);
methods:-

        Same as it's base class.

Char oriented Streams

1) Writer
        It is an abstract class and it is the super class for all the char-oriented o/p stream classes.
methods:-
public void write(int);
public void write(char[]);
public void write(char[],int offset,int length);
public void write(String);
public void close();
2) Reader
              It is an abstract class and it is the super class for all the char-oriented i/p stream classes.



methods:-
public int read();
public int read(char[]);
public int read(char[],int offset,int length);
public long skip(long);
public void close();

Sunday, 4 December 2016

Java - PrintStream

9) PrintStream
        It is used to write any type of data to the particular o/p stream.
        When we use constructors and methods of this class, no need to throw IOException.
constructors:-
PrintStream(OutputStream);
PrintStream(OutputStream,boolean flushstate);
methods:-
public void print(int);(for all datatypes).
public void print(String);
public void print(Object);
public void println(int);(for all datatypes).
public void println(String);

public void println(Object);

Java - DataInputStream and DataOutputStream

7) DataOutputStream
        To write primary datatypes to the particular o/p stream as encoded format.
constructor:-
DataOutputStream(OutputStream);
methods:-
public void writeShort(short);
public void writeInt(int);
public void writeLong(long);
public void writeDouble(double);
public void writeFloat(float);
public void writeBoolean(boolean);
public void writeChar(char);
public void writeByte(byte);
8) DataInputStream
        To read primary datatypes from the particular i/p stream as decoded format.
constructor:
DataInputStream(InputStream);
methods:-
public short readShort();
public int readInt();
public long readLong();
public double readDouble();
public float readFloat();
public boolean readBoolean();
public char readChar();

public byte readByte();

Java - BufferedInputStream and BufferedOutputStream

5) BufferedOutputStream
        It is used to write data to particular o/p stream and to avoid system call(OS) occurence for every process.
constructor:-
BufferedOutputStream(OutputStream);
BufferedOutputStream(OutputStream,int bufsize);
methods:-
        They're same as it's base class.
6) BufferedInputStream
        It is used to read data from particular i/p stream and to avoid system call(OS) occurence for every process.
constructor:-
BufferedInputStream(InputStream);
BufferedInputStream(InputStream,int bufsize);
methods:-

        They're same as it's base class.

Java - FileInputStream and FileOutputStream

3)FileOutputStream
        To write data to particular file.
constructors:-
FileOutputStream(String filepath&name);//c:/first.txt
FileOutputStream(String path,String filename);//c:/,first.txt
FileOutputStream(File);
methods:-
        They're same as it's base class.
4)FileInputStream
        To read data from particular file.
constructors:-
FileInputStream(String filepath&name);
FileInputStream(String path,String filename);
FileInputStream(File);
methods:-

        They're same as it's base class.

Java - Streams

Streams:-
        It is a flow of data.
        It is a path of communication between source and destination.
2 Types
        1) Byte Oriented Stream (ASCII Code format)
        2) Character Oriented Stream (Unicode format)
Byte Oriented Stream
InputStream:
        To read the data from particular i/p device such as keyboard,file and socket.
OutputStream:
        To write the data to the particular o/p device such as monitor,file and socket.
classes:-
1) OutputStream
        It is an abstract class and it is the super class for all the byte-oriented o/p stream classes.
methods:-
public void write(int);
public void write(byte[]);
public void write(byte[],int offset,int length);
public void flush();//clear the stream.
public void close();
2) InputStream
        It is an abstract class and it is the super class for all the byte-oriented i/p stream classes. It is used to read the data from particular i/p device.
methods:-
public int read();
public int read(byte[]);
public int read(byte[],int offset,int length);
public long skip(long);
public long available();

public void close();

Java - Introduction About Stream Class

Byte Oriented Hierarchical

object
1)OutputStream
        1)FileOutputStream
        2)FilterOutputStream
                1)DataOutputStream
                2)BufferedOutputStream
                3)PrintStream
               
        3)ObjectOutputStream
2)InputStream
        1)FileInputStream
        2)FilterInputStream
                1)DataInputStream
                2)BufferedInputStream
        3)ObjectInputStream
Character Oriented Hierarchical
Object
1)Writer
        1)FileWriter
        2)BufferedWriter
        3)PrintWriter
2)Reader
        1)FileReader
        2)BufferedReader

        3)InputStreamReader

Facebook Page

https://www.facebook.com/Java-Corner-582506591874425/

Java - File functions and FilenameFilter class

methods:-
public long length();
public String getName();
public String getParent();
public String getPath();
public boolean exists();
public boolean isDirectory();
public boolean isFile();
public boolean isHidden();
public boolean mkdir();
public boolean delete();
public void renameTo(File);
public String[] list();
public String[] list(FilenameFilter);
        Here FilenameFilter is an interface.
FilenameFilter
        To filter particular files & folders.
method:-

public boolean accept(File,String);

Java - File Class

Files
        It is a collection of records.
java.io.File
        It is a class of java.io package which defines several methods to manipulate some operations on files & directories.
constructors:-
File(String path&filename); //d:/demo.txt
File(String path,String filename); //d:/ , demo.txt

File(File); 

Java - Packages

Package
i) Syntax to create a package:-
package <pkgname>;
        pkgname should be same as current directory and this statement should be written at very first line of the program.
        Then we may import required packages and define classes and interfaces as required.
        Then compile them.
       



ii) Using user-defined pkg in a pgm:-
        import required user-def pkg.
        then use corresponding classes in our program.
        Before we compile this program, we have to set classpath as following method:-

set classpath=%classpath%;path of pkg;.;

Java - Exception Definition

        we can write set of executable sts within a try block which should be follwed by atleast one catch block or finally block.
        try block can have more than one catch blocks.
        if an exception is occured by a statement within a try block , then corresponding instance is created and which will be thrown to corresponding catch block.
        we can also throw an exception explicitly using the keyword "throw".
        even exceptions are handled or not, the statements within a finally block will be executed.
        we can throw checked exceptions using the keyword "throws".

constructor of class Exception:-
Exception();
Exception(String);
method:-

public String getMessage();

Java - Syntax for Exception Handling

syntax to try,catch and finally block:-
try
   {
        set of exe sts;
        .
        .
        if(condition)
        throw new classname();//optional
        throw new classname("args");//optional
        .
   }
catch(childclassname oname)
   {
        .
   }
.
catch(baseclassname oname)
   {
        ………..
   }
finally
  {
        write statements;

  }

Java - Exception Handling

Exception Handling:-
        Exception is an abnormal condition, if it is occured in our program, then program will be terminated suddenly.
        To overcome this problem, we have some exception handlers in java program, such as try,catch,throw,throws and finally.
        Exceptions are occured at runtime.
        Basically, a java program may face two kinds of abnormal conditions. such as, Error and Exception.
        Exceptions are handled by java program whereas Errors can not be trapped.
        Error
§  NoSuchMethodError
§  NoClassDefFoundError
        Usually, we have two types of Exception.
        i) Checked Exception
                They are checked at compilation time.
        eg:
        IOException, ClassNotFoundException,         SQLException,UnKnownHostException.
        ii) Unchecked Exception
        They are checked at runtime.
        eg:- 
·       NumberFormatException
·       ArithmeticException
·       NullPointerException
·       ArrayIndexOutOfBoundsException

·       NegativeArraySizeException.etc.,

Java - final Keyword

final :(keyword)
        final class cannot be inherited
        final method cannot be overridden
        final variable cannot be changed

Java - Interface

Interface:-
        It is like as abstract class but one exception that in which all the methods cannot have body.
        All the methods of an interface are public and abstract by default.
        All the methods of an interface should be defined(implemented) by its derived class.
        All the variables declared with in an interface are public,static and final by default.
        Since interface can not be instantiated,it should have atleast one derived class.
        To achieve "pure dynamic polymorphism".
        A class can inherit more than one interfaces using the keyword "implements".
        An interface can inherit another interface using the keyword "extends".
syntax to define an interface:-
<specifier> interface <interfacename>
   {
        methods decl;
        constant fields decl&init;
   }

<specifier>class childclassname implements interfacename1,interfacename2
{
        interface method definition
        class own method definition

}

Java - Abstract class

Abstract class:-
        A class can have a method(no body of the function), then that should be declared as abstract method and whose class should be declared as abstract class.
        An abstract class can have both abstract and non-abstract methods.
         Since abstract class can not be instantiated, it should have atleast one derived class.
        Abstract methods should be overridden by derived classes whereas non-abstract methods may or may not be overridden by derived classes.
        It is used to achieve dynamic polymorphism.
        Syntax
        ======
        accesspecifier abstract class classname
        {
        accessspcifier abstract rtype mname(arg,,,,);
        non abs method definition(instance & static)

        }

Java - Dynamic Polymorphism

Dynamic polymorphism:-(Runtime polymorphism)
        Methods are binding to an object during runtime.
Method overriding:-
        A class can have a method which name is same as method name of it's base class including same args,same data types and same return type(ie same signature).
        Derived class can modify the statements of its base class using overriding.
        To achieve dynamic polymorphism.
Dynamic method dispatch:-
        An object of a class can refer instance of itself and instance of it's derived classes.
        By using this object, we can invoke  overridden methods only, because of it refers methods of its type, but invokes methods of which instance has referred(assigned) now.
        methods are resolved(determined) at runtime.


Java-Polymorphism

Polymorphism (Many forms)
        It means that one interface, Multiple actions.
        It is used for common class of actions.
        Common methods are used.
Types:-
i) Static polymorphism (or)compile (or)early binding.
ii) Dynamic polymorphism (or) runtime (or)late binding.
i) Static polymorphism:-(Compile time polymorphism)
        Methods are binding to an object during compilation time.
        Constructor overloading and method overloading are examples of static polymorphism.
Method overloading:-

        A class or its derived class can have more than one methods with same name but they differ with no.of args or data type of the args and order of the args.

Java - Inheritance in Contructor

Invoking constructor of  base class in derived class:-
        "super" is a keyword to invoke constructor of base class and also asccess members of base class.
eg:-
super();//default constructor
super(args);//parameterized constructor
        This statement should be written at very first line of the derived class constructor.
To invoke & access members of base class:
        super.variablename;

        super.methodname(args);

Java - Inheritance Explanation

ü To create a new class from an existing class.
ü Common properties are derived from base class.
ü It is used for Reusability and Extensibility.
Types:-
i) Single level inheritance.
ii) Multi-level inheritance.
iii) Hierarchical inheritance.
Syntax to inherit a class:-
<specifier> class <childclsname> extends <baseclsname>
   {
        Data member decl&init;
        member fn defn;
   }
eg:-
class A
{
}
class B extends A
{

}

Access Specifiers

Access specifiers:-
They determine visibility,accessibility and scope of members of a class in other classes.
private:-
        private members can be accessed by members of that class only.
public:-
        public members can be accessed by members of all the classes in any packages.
protected:-
        protected members can be accessed by members of all the classes in same package and members of derived classes only in other packages.
No specifier/No modifier/Weaker Access specifier : (default)

        They can be accessed by members of all the classes of same package only.

Java - StringBuffer Explanation

Methods
        Same as String class method and other methods are,
        public Synchronized StringBuffer append(int);            
        public Synchronized StringBuffer insert(int offset,Object);
        public Synchronized StringBuffer delete(int startindex,int endindex);
        public Synchronized StringBuffer deleteCharAt(int index);
        public Synchronized StringBuffer replace(int startindex,int endindex,String data);
        public Synchronized void setCharAt(int index,char ch);

        public Synchronized StringBuffer reverse();

Java - String Functions

constructors:-
String();
String(String);
String(char[]);
String(char[],int offset,int length);
String(byte[]);
String(byte[],int offset,int length);
String(StringBuffer);
Methods of String class:-
public int length();
public char charAt(int index);
public int indexOf(char);
public int indexOf(char,int searchindex);
public int indexOf(String);
public int lastIndexOf(char);
public int lastIndexOf(char,int searchindex);
public int lastIndexOf(String);
public String trim();
public String toLowerCase();
public String toUpperCase();
public String substring(int index);
public String substring(int startindex,int endindex);
public int compareTo(String);
public int compareToIgnoreCase(String);
public boolean equals(String);
public boolean equalsIgnoreCase(String);
public boolean startsWith(String);
public boolean endsWith(String);
public java.lang.String concat(java.lang.String);
public java.lang.String replace(char, char);
public java.lang.String[] split(java.lang.String);
public byte[] getBytes();
public char[] toCharArray();
public static String valueOf(short);
public static String valueOf(int);
public static String valueOf(long);
public static String valueOf(float);

public static String valueOf(double);

Featured post

Development Of JAVA Program