Core Java Tutorial

Difference between JVM,JRE,JDK
JVM → is A Spcification
JRE → Implementation of JVM
JDK →  JRE+Some other tools
local → Must be Intialize
instance, static→ Def. values


OOPS(object Orieted Programming)
Method Overloading and TypePromotion
One type is promoted to another implicitly if no matching datatype is found.
sum(int a, long b)
sum(int a, int b)
→  if sum(20,20) is declare if, there is no sum(int,int) method it go to int(int,long)


1.Constructor
Constructor is invoked at the time of object creation
1) Default Constructor
If there is no constructor in a class, compiler automatically creates a default constructor.
Default constructor provides the default values to the object like 0, null etc. depending on the type.
2)Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Parameterized constructor is used to provide different values to the distinct objects.


Constructor Overloading
a class can have any number of constructors that differ in parameter lists.The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.


2.static keyword
The static keyword is used in java mainly for memory management
The static keyword belongs to the class


The static can be:


  • variable (also known as class variable)
  • method (also known as class method)
  • block
  • nested class


1) static variable
  • The static variable can be used to refer the common property of all objects
  • The static variable gets memory only once in class area at the time of class loading.


2) static method
  • A static method can be invoked without the need for creating an instance of a class.
  • The static method can not use non static data member or call non-static method directly.
  • this and super cannot be used in static context.


3)static block
  • Is used to initialize the static data member.
  • It is executed before main method at the time of class loading.
3.this keyword
refers to the current class object.


  • this keyword can be used to refer current class instance variable.
  • this() can be used to invoke current class constructor.
  • this keyword can be used to invoke current class method (implicitly)
  • this can be passed as an argument in the method call.
  • Call to this() must be the first statement in constructor.




4.super keyword
The super is a reference variable that is used to refer immediate parent class object
super() is added in each class constructor automatically by compiler.


Usage of super Keyword
  • super is used to refer immediate parent class instance variable.
  • super() is used to invoke immediate parent class constructor.
  • super is used to invoke immediate parent class method.


5.Inheritance [ IS-A Relationship]
Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent object.


Used for:
  • For Method Overriding (So Runtime Polymorphism).
  • For Code Reusability.



6.Aggregation in Java [ HAS-A Relationship ]
The Process of Declaring a Others Class Object as a datamemeber of the current class


Example, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.






7.Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.
  • Method Overriding is used for Runtime Polymorphism
  • method must have same name as in the parent class
  • method must have same parameter as in the parent class.
  • must be IS-A relationship (inheritance).


8.Initializer block:
→ it will Exceute before Contructor,  
→ It will exceute each and Evry time while creating object


There are mainly three rules for the instance initializer block.
  • initializer block is created when instance of the class is created.
  • initializer block is invoked after the parent class constructor is invoked (after super() constr. call).
  • The instance initializer block comes in the order in which they appear.









9.Final Keyword
The final keyword in java is used to restrict the user. The final keyword can be used in
  1. variable
  2. method
  3. class
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).


2) final method
If you make any method as final, you cannot override it.


3) final class
If you make any class as final, you cannot extend it.


blank final variable
A final variable that is not initialized at the time of declaration is known as blank final variable.
It can be initialized only in constructor.


static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block.

9.Runtime Polymorphism
The process of overriding parent class methods in Derived class is Known as Run time Polymorphism
Runtime polymorphism can't be achieved by data members.


10.Static Binding and Dynamic Binding
“Dynamic binding is a mechanism of binding an appropriate version of a derived class which
is inherited from base class with base class object”


1.static binding
When type of the object is determined at compiled time(by the compiler), it is known as static binding.
2.Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
11.instanceof operator
The instanceof operator is also known as type comparison operator because it compares the instance with type.It compaires the Object belongs to given class or Not.
It returns either true or false
12.Package
A package is a group of similar types of classes, interfaces and sub-packages


To Compile : javac -d . Simple.java
To Run : java mypack.Simple


13.Encapsulation


Encapsulation is a process of wrapping code and data together into a single unit
e.g. capsule i.e mixed of several medicines.
Java Bean is the example of fully encapsulated class.  

14.Object class


The Object class is the parent class of all the classes in java bydefault. In other words, it is the topmost class of java.
  1. native Object clone() :Creates a new object of the same class as this object.
  2. boolean equals(Object obj):Compares two Objects for equality.
  3. protected void finalize():Called by the garbage collector on an object when garbage                collection determines that there are no more references to the object.
  4. final native Class getClass():Returns the runtime class of an object.
  5. native int hashCode() :Returns a hash code value for the object.
  6. final native void notify() :Wakes up a single thread that is waiting on this object's monitor.
  7. final native void notifyAll():Wakes up all threads that are waiting on this object's monitor.
  8. public String toString() :Returns a string representation of the object.
  9. native void wait() :Waits to be notified by another thread of a change in this object.
  10. native void wait(long) :Waits to be notified by another thread of a change in this object.
  11. native void wait(long, int) :Waits to be notified by another thread of a change in this object.


(i).Cloning
cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
Steps:
1.Class mustbe implement java.lang.Clonable interface for participate in Cloning.
2.If we don't implement Cloneable, clone() method generates CloneNotSupportedException.
3.Override clone method with super.clone(), other wise it gives clone() not visible error


The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.
Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.


15.strictfp keyword(floting point precision)
The strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. Without using strictfp keyword, the floating point precision depends on target platform’s hardware


YES : The strictfp keyword can be applied on methods, classes and interfaces.
NO  :The strictfp keyword can not be applied on abstract methods, variables or constructors.

→ Creating API Document | javadoc tool  command: javadoc M.java

                                                       String Handling
Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.


There are two ways to create String object:
 1.By string literal : String s="Hello";  
Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:


   String s1="Welcome";  
   String s2="Welcome";//no new object will be created  
2. By new keyword : String s1=new String("Welcome");  


1.Immutable String:
In java, strings are immutable (unmodifiable) objects.
For example:








2.String comparison
1.By equals() method
2.By = = operator
3.By compareTo() method
1.equals() method compares the original content of the string
public boolean equals(Object another): compares this string to the specified object.
public boolean equalsIgnoreCase(String): compares another String, ignoring case.
2) By == operator:
The = = operator compares references not values.

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. Suppose s1 and s2 are two string variables.If:
   s1 == s2 :0
   s1 > s2   :positive value
   s1 < s2="">  :negative value


3.Methods:


1) boolean equals(Object anObject) Compares this string to the specified object.
2) boolean equalsIgnoreCase(String another)Compares this String to another String, ignoring case.
3) String concat(String str) Concatenates the specified string to the end of this string.
4) int compareTo(String str) Compares two strings and returns int
5) int compareToIgnoreCase(String str)Compares two strings, ignoring case differences.
6) String substring(int beginIndex)Returns a new string that is a substring of this string.
7) String substring(int begin,int endIndex)Returns a new string that is a substring of this string.
8) String toUpperCase()Converts all of the characters in this String to upper case
9)String toLowerCase()Converts all of the characters in this String to lower case.
10) String trim()Returns a copy of the string, with leading and trailing whitespace omitted.
11) boolean startsWith(String prefix)Tests if this string starts with the specified prefix.
12) boolean endsWith(String suffix)Tests if this string ends with the specified suffix.
13) char charAt(int index)Returns the char value at the specified index.
14) int length() Returns the length of this string.
15) String intern()Returns a canonical representation for the string object.


4.StringBuffer ::(Mutable- Thread Safe)
The StringBuffer class is used to created mutable (modifiable) string. The StringBuffer class is same as String except it is mutable i.e. it can be changed.


StringBuffer class is thread-safe i.e. multiple threads cannot access it simultaneously .So it is safe and will result in an order.


  •    StringBuffer(): creates an empty string buffer with the initial capacity of 16.
  •    StringBuffer(String str): creates a string buffer with the specified string.
  •    StringBuffer(int capacity): creates an empty string buffer with the specified capacity as length.











4.StringBuilder class:(Mutable- Not Thread Safe)
The StringBuilder class is used to create mutable (modifiable) string. The StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK1.5.
Commonly used Constructors of StringBuilder class:


   StringBuilder(): creates an empty string Builder with the initial capacity of 16.
   StringBuilder(String str): creates a string Builder with the specified string.
   StringBuilder(int length): creates an empty string Builder with the specified capacity as length.


5.StringTokenizer
The java.util.StringTokenizer class  break a string into tokens. It is simple way to break string.









                                                         


                                             




StringTokenizer class is deprecated now. It is recommended to use split() method of String class or regex (Regular Expression).


                                          Exception Handling


Checked exceptions are checked at compile-time.
Unchecked exceptions are not checked at compile-time rather they are checked at runtime.


  1. For each try block there can be zero or more catch blocks, but only one finally block.
  2. The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
  3. At a time only one Exception is occured and at a time only one catch block is executed.


1.throw keyword
The throw keyword is used to explictily throw an exception. We can throw either checked or uncheked exception. The throw keyword is mainly used to throw custom exception


2.throws keyword:
The throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.


UserDefiend Exception:
1.Take a UserDefiendException class which extends java.lang.Error, java.lang.Exception
2.Class must contain String parameterized constructor and also calls super(-) , for Exceptional message.

3.Take one UserDefiendExceptionSUbclass which comtaims a method , and that Throws a Mesage with the Constrcutor


Ex:


                                                     Nested classes (Inner classes)                           Ratan


There are two types of nested classes non-static and static nested classes.
The non-static nested classes are also known as inner classes.
      1.non-static nested class(inner class)
       a)Member inner class :A class that is declared inside a class but outside a method is known as member inner cls
       b)Annomynous inner class:A class that have no name is known as annomymous inner class.
       c)Local inner class:A class that is created inside a method is known as local inner class


       2.static nested class:Static inner classes can access only static variables and static methods it does not access the                  nstinstance variables and instance methods.
Uses of nested classes:-
1. It is the way logically grouping classes that are only used in the one place.
2. It increase the encapsulation


Member inner classes:-
1. If we are declaring any data in outer class then it is automatically available to inner classes.
2. If we are declaring any data in inner class then that data is should not have the scope of the outer class.








                                             Multithreading
             Threads share a common memory area. They don't allocate separate memory area so save memory, and context-switching between the threads takes less time than processes.
Multithreading is mostly used in games, animation etc.  Note:At a time only one thread is executed.





1.New state: It is one in which the thread about to enter into main memory.
2.Ready state: Thread is entered into memory space allocated and it is waiting for CPU for executing.
3.Running state: the thread is under the control of CPU.
4.Waiting state: It is one in which the thread is waiting because of the following factors:
a) CPU burst time of the thread (CPU burst time is an amount of the required by the thread by the CPU).
b) Make the thread to sleep for sleep for some specified amount of time.
c) Make the thread to suspend.
d) Make the thread to wait for a period of time.
e) Make the thread to wait without specifying waiting time.
5.Halted state: It is one in which the thread has completed its total execution.


As long as the thread is in new and halted states whose execution status is false where as
when the thread is in ready, running and waiting states that execution states is true.


public void run ():
Any JAVA programmer want to define a logic for the thread that logic must be defined only
run () method. When the thread is started, the JVM looks for the appropriate run () method for
executing the logic of the thread. Thread class is a concrete class and it contains all defined methods
and all these methods are being to final except run () method. run () method is by default contains a
definition with null body. Since we are providing the logic for the thread in run () method. Hence it
must be overridden by extending Thread class into our own class


public final void start ():
This is the method which is used for making the Thread to start to execute the thread logic.
The method start is internally calling the method run ().


public final void suspend ():
This method is used for suspending the thread from current execution of thread. When the
thread is suspended, it sends to waiting state by keeping the temporary results in process control
block (PCB) or job control block (JCB).
public final void resume ():
This method is used for bringing the suspended thread from waiting state to ready state.
When the thread is resumed to start executing from where it left out previously by retrieving the
previous result from PCB.
public final void stop ():
This method is used to stop the execution of the current thread and the thread goes to
halted state from running state. When the thread is restarted it starts executing from the beginning
only.
public final void wait (long msec):
This method is used for making the currently executing thread into waiting state for a period
of time. Once this period of time is over, automatically the waiting thread will enter into ready state
from waiting state.


public static void sleep (long msec) throws InterruptedException method is used (waiting
state). If the sleep time is over automatically thread will come from waiting state to ready state.
For example:Thread.sleep (1000);


public static Thread currentThread () is used for obtaining the threads which are running in the
main memory of the computer.
For example:Thread t=Thread.currentThread ();

Daemon thread : is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM termintates this thread automatically.


The java.lang.Thread class provides two methods related to daemon thread


   public void setDaemon(boolean status): To mark the current thread as daemon thread or user thread.
   public boolean isDaemon(): is used to check that current is daemon.


Deadlock:
Deadlock can occur in a situation when a thread is waiting for an object lock, that is acquired by another thread and second thread is waiting for an object lock that is acquired by first thread. Since, both threads are waiting for each other to release the lock, the condition is called daedlock.
















                                                 IO Streams


In order to store the data permanently in the form of files we must use or import a package
called java.io.*
Input → Input to Main Memory (  Read INPUT  )
Output → Output from Main Memory (  Write OUTPUT  )
Types of Steams:


Byte- Streams :  Read/ Write Data by Byte by Byte
Character- Streams :  Read/ Write Data by Character by Character



FileXxxSteams  → Used for perform operations using Files
DataXxxStreams → Used for Perform operations using Keyboard. So we must pass inputStream for reading data from Keyboard



Serialization: Serialization is the process of saving the state of the object permanently in the form of a file.
De-Serialization : De-serialization is a process of retriving the data from the file in the form of object.


  1. For Serilization class must implemebnt java.io.Serializable interface
  2. Must have Setter& Getter methods for Datamembers

Types of serialization:
1.Complete serialization :  all the data members of the class participates in serialization process.


2.Selective serialization :few data members of the class participating in serialization process.
In order to avoid the variable from the serialization process, make that variable
declaration as transient i.e., transient variables never participate in serialization process.


3.Manual serialization: the user defined classes always implements java.io.Serializable interface.
4.Automatic serialization : the object of sub-class of Serializable sub-class participates in
serialization process.
Buffered Streams:
Buffered streams are basically used to reduce physical number of read and write operation
i.e., buffered streams always increases the performance of ordinary streams


BufferedInputStream:
FileInputStream fis=new FileInputStream (“abc.dat”);
BufferedInputStream bis=new BufferedInputStream (fis);


BufferedOutputStream:
FileOutputStream fos=new FileOutputStream (“abc.dat”);
BufferedOutputStream bos=new BufferedOutputStream (fos);

















1.LinkedList:
The data is organized in LinkedList in the form of nodes. The node contains two parts, they
are data part, address part.
Disadvantages of LinkedList:
1. Additional memory space is created for address part of the node in heap memory.
2. Retrieval time is more.
3. Since, we are wasting most of the memory space for addresses, performance will be
reduced.


2.java.util.ArrayList:
ArrayList is also concrete sub-class of collection framework classes whose object allows us to
organize the data either in similar type or in different type.
Advantages of ArrayList over LinkedList:
1. No additional memory space is required for data of ArrayList.
2. Retrieval time is quite faster.
3. Performance is high. Since, there is no memory space is required for maintaining address of
data of ArrayList.











java.util.SortedSet:
SortedMap extends Map. An object of SortedMap displays the data by default in sorted
order.


                                             Java New Features by Version    
1.4 :Assertion (Java 4)


Java 5.0
  1.    For-each loop (Java 5)
  2.    Varargs (Java 5)


  1.    Static Import (Java 5)


  1.    Autoboxing and Unboxing (Java 5)
AutoBoxing
Automatic conversion from primitive to wrapper object by the compiler is called “AutoBoxing.”
Integer I = 10;
[Compiler Automatically converts primitive to Integer Object form]


AutoUnBoxing
Automatic conversion from wrapper object to primitive type by the compiler is calles
“AutoUnBoxing”
int i = new Integer(10);
[Compiler Automatically converts Integer Object to int primitive.]
  1.    Enum (Java 5)
  2.    Covariant Return Type (Java 5)
  3.    Annotation (Java 5)
  4.    Generics (Java 5)
Java  7.0
  1.    String in switch statement (Java 7)
  2.    Binary Literals (Java 7)
  3.    The try-with-resources (Java 7)
  4.    Caching Multiple Exceptions by single catch (Java 7)
  5. Underscores in Numeric Literals (Java 7)


native methods
The methods which are implemented in non-java are called “native methods” or “foreign methods”.
native is the modifier applicable only for methods.we can’t declare classes and variables as native
public native void m1(); //Declaring a native method.


Transient Modifier
Transient is the keyword applicable only for variables. transient variable cannot participate in serialization and De-serilization process;
1.Serialization The Process of Saving an object to a file is called “serialization”. But strictly
speaking serialization is the process of converting an object from java supported format to network
or file supported format.
2.DeSerialization The process of reading an object from a file is called deserialization. But strictly
speaking it is the process of Converting an object from network supported format or file supported
format to java supported format


VolatileModifier
Volatile is the keyword applicable only for variables. We can’t declare methods and classes with
volatile modifier.


If the value of a variable keep on changing then we have to declare that variable as volatile.
For the volatile variable JVM will create a separate local copy for every thread.
All the intermediate calculation performed by that thread will be referred in local copy instead of
master copy ,once the value got finalized just before terminating the thread the local copy value
updated in the master copy. So that remaining threads will always get a stable value.
The main advantage of volatile keyword is we can overcome “Data Inconsistency” problems.
Creating and maintaining separate copy for every thread will increase complexity and effect
performance of the system.
volatile and final is illegal combination for the variables.





Difference Between final, finally, finalize
final: It is the modifier applicable for classes methods and variables. For final classes we can’t create
child classes i.e inheritance is not possible.
final() methods can’t be override in child classes for final variables reassignments is not possible
because they are constants.


finally: It is a block associated with try catch the main objective of finally block is to maintain
cleanup code which should execute always.


finalize: It is a method should be executed by the “Garbage Collector” just before destroying an
object. The main objective of finalize method is to maintain cleanup code.
wildcard
a collection whose element type matches anything. It's called a wildcard type for obvious reasons. We can write:
void printCollection(Collection<?> c) {
   for (Object e : c) {
       System.out.println(e);
   }}


INTERNATIONALIZATION(I18N)
It is the process of developing web application so that it can be used in any environment. That supports
various languages and various countries, with out making any changes in the application we can achieve this
by using following classes.
1) Locale : To represent a particular region.
2) NumberFormat : For formatting Numbers.
3) DateFormat : For formatting Dates.


1.Java Reflection API(java.lang.Class)
Reflection is the process of examining or modifying the runtime behaviour of a class at runtime.
Reflection API is mainly used in:
  • IDE (Integreted Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
  • Debugger
  • Test Tools etc.


1)  String getName() returns the class name
2)  static Class forName(String className)throws ClassNotFoundException loads the class and returns the reference of Class class.
3)  Object newInstance()throws InstantiationException,IllegalAccessException creates new instance.
4)  boolean isInterface() checks if it is interface.
5)  boolean isArray() checks if it is array.
6)  boolean isPrimitive() checks if it is primitive.
7)  Class getSuperclass() returns the superclass class reference.
8)  Field[] getDeclaredFields()throws SecurityException: returns the total number of fields of this class.
9)  Method[] getDeclaredMethods()throws SecurityException returns the total number of methods of this class.
10)  Constructor[] getDeclaredConstructors()throws SecurityException returns the total number of constructors of this class.
11)  Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException returns the method class instance.


                                     RMI(Remote Method Invocation)
The RMI allows an object to invoke methods on an object running in another JVM.
The Remote Method Invocation (RMI) is an API that provides a mechanism to create distributed application in java.


The RMI provides remote communication between the applications using two objects stub and skeleton.


1.stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object. When the caller invokes method on the stub object, it does the following tasks:
  • It initiates a connection with remote Virtual Machine (JVM),
  • It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
  • It waits for the result
  • It reads (unmarshals) the return value or exception, and
  • It finally, returns the value to the caller.


2.Skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it. When the skeleton receives the incoming request, it does the following tasks:
  • It reads the parameter for the remote method
  • It invokes the method on the actual remote object, and
  • It writes and transmits (marshals) the result to the caller.


Needs RMI Tool..so stooped...


The is given the 6 steps to write the RMI program.
  1. Create the remote interface
  2. Provide the implementation of the remote interface
  3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
  4. Start the registry service by rmiregistry tool
  5. Create and start the remote application
  6. Create and start the client application











2 comments

This comment has been removed by the author.

Finding the time and actual effort to create a superb article like this is great thing. I’ll learn many new stuff right here! Good luck for the next post buddy..
Java Training in Chennai