Sunday, 14 May 2017

Java Applet ~ mkniit

Applet in Java Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as apart of a web document. Any applet in Java is a class that extends the java.applet.Applet class. An Applet class does not have any main() method. It is viewed using JVM. The JVM can use either a plug-in of the Web browser or a separate runtime environment to run an applet application. JVM creates an instance...
Read More »

Java Legacy Classes ~ mkniit

Legacy Classes Early version of java did not include the Collection framework. It only defined several classes and interface that provide method for storing objects. When Collection framework were added in J2SE 1.2, the original classes were reengineered to support the collection interface. These classes are also known as Legacy classes. All legacy claases and interface were redesign by JDK 5 to support Generics. The following are the legacy classes defined by java.util package Dictionary HashTable Properties Stack Vector There...
Read More »

Java Comparator Interface ~ mkniit

In Java, Comparator interface is used to order the object in your own way. It gives you ability to decide how element are stored within sorted collection and map. Comparator Interface defines compare() method. This method compare two object and return 0 if two object are equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is return. The method can throw a ClassCastException if the type of object are not compatible for...
Read More »

Java Map Interface ~ mkniit

A Map stores data in key and value association. Both key and values are objects. The key must be unique but the values can be duplicate. Although Maps are a part of Collection Framework, they can not actually be called as collections because of some properties that they posses. However we can obtain a collection-view of maps. InterfaceDescription MapMaps unique key to value. Map.EntryDescribe an element in key and value pair in a map. This is an inner class of map. NavigableMapExtends...
Read More »

Java Iterator and ListIterator ~ mkniit

Accessing a Collection To access, modify or remove any element from any collection we need to first find the element, for which we have to cycle throught the elements of the collection. There are three possible ways to cycle through the elements of any collection. Using Iterator interface Using ListIterator interface Using for-each loop Accessing elements using Iterator Iterator Interface is used to traverse a list in forward direction, enabling you to remove or modify the elements...
Read More »

Java Collection Classes ~ mkniit

The Collection classes Java provides a set of Collection classes that implements Collection interface. Some of these classes provide full implementations that can be used as it is and other abstract classes provides skeletal implementations that can be used as starting points for creating concrete collections. ArrayList class ArrayList class extends AbstractList class and implements the List interface. ArrayList supports dynamic array that can grow as needed....
Read More »

Java Collection Interfaces ~ mkniit

Interfaces of Collection Framework The collection framework has a lot of Interfaces, setting the fundamental nature of various collection classes. Lets study the most important Interfaces in the collection framework. The Collection Interface It is at the top of collection heirarchy and must be implemented by any class that defines a collection. Its general declaration is,interface Collection < E > Following are some of the commonly used methods in this interface. MethodsDescription add(...
Read More »

Java Introduction to Collection ~ mkniit

Collection Framework Collection framework was not part of original Java release. Collections was added to J2SE 1.2. Prior to Java 2, Java provided adhoc classes such as Dictionary, Vector, Stack and Properties to store and manipulate groups of objects. Collection framework provides many important classes and interfaces to collect and organize group of alike objects. Important Interfaces of Collection API InterfaceDescription CollectionEnables you to work with groups of object;...
Read More »

Java Generics ~ mkniit

A class or interface that operates on parameterized type is called Generic. Generics was first introduced in Java5. Now it is one of the most profound feature of java programming language. It provides facility to write algorithm independent of any specific type of data. Generics also provide type safety. Using Generics, it becomes possible to create a single class or method that automatically works with all types of data(Integer, String, Float etc). It expanded the ability...
Read More »

Java Java Networking ~ mkniit

Networking in Java Java is a premier language for network programming. java.net package encapsulate large number of classes and interface that provides an easy-to use means to access network resources. Here are some important classes and interfaces of java.net package. Some Important Classes CLASSES CacheRequestCookieHandler CookieManagerDatagrampacket Inet AddressServerSocket SocketDatagramSocket ProxyURL URLConnecti...
Read More »

Java Serialization ~ mkniit

Serialization and Deserialization in Java Serialization is a process of converting an object into a sequence of bytes which can be persisted to a disk or database or can be sent through streams. The reverse process of creating object from sequence of bytes is called deserialization. A class must implement Serializable interface present in java.io package in order to serialize its object successfully. Serializable is a marker interface that...
Read More »

Java I/O Stream ~ mkniit

IO Stream Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to make input and output operation in java. In general, a stream means continuous flow of data. Streams are clean way to deal with input/output without having every part of your code understand the physical. Java encapsulates Stream under java.io package. Java defines two types of streams. They are, Byte Stream : It provides a convenient means for handling input...
Read More »

Java Autoboxing and Unboxing ~ mkniit

type wrapper Java uses primitive types such as int, double or float to hold the basic data types for the sake of performance. Despite the performance benefits offered by the primitive types, there are situation when you will need an object representation. For example, many data structures in Java operate on objects, so you cannot use primitive types with those data structures. To handle these situations Java provides type Wrappers which provide classes that encapsulate a primitive...
Read More »

Java Enumerations ~ mkniit

Enumerations was added to Java language in JDK5. Enumeration means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using enum keyword. Each enumeration constant is public, static and final by default. Even though enumeration defines a class type and have constructors, you do not instantiate an enum using new. Enumeration...
Read More »

Java Interthread Communication ~ mkniit

Java provide benefit of avoiding thread pooling using interthread communication. The wait(), notify(), notifyAll() of Object class. These method are implemented as final in Object. All three method can be called only from within a synchronized context. wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor and call notify. notify() wakes up a thread that called wait() on same...
Read More »

java Synchronization ~ mkniit

At times when more than one thread try to access a shared resource, we need to ensure that resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. The synchronization keyword in java creates a block of code referred to as critical section. Every Java object with a critical section of code gets a lock associated with the object. To enter critical section a thread need to obtain the corresponding object's lock. General...
Read More »

Java Joining a thread ~ mkniit

Joining threads Sometimes one thread needs to know when another thread is ending. In java, isAlive() and join() are two different methods to check whether a thread has finished its execution. The isAlive() method returns true if the thread upon which it is called is still running otherwise it returns false. final boolean isAlive() But, join() method is used more commonly than isAlive(). This method waits until the thread...
Read More »

Java Creating a thread ~ mkniit

Java defines two ways by which a thread can be created. By implementing the Runnable interface. By extending the Thread class. Implementing the Runnable Interface The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form, public void run() run() method introduces a concurrent thread into your program. This thread...
Read More »

Java Thread class ~ mkniit

Thread class is the main class on which Java's Multithreading system is based. Thread class, along with its companion interface Runnable will be used to create and run threads for utilizing Multithreading feature of Java. Constructors of Thread class Thread ( ) Thread ( String str ) Thread ( Runnable r ) Thread ( Runnable r, String str) You can create new thread, either by extending Thread class or by implementing Runnable...
Read More »

Java Multithreading ~ mkniit

Introduction to Multithreading A program can be divided into a number of small processes. Each small process can be addressed as a single thread (a lightweight process). Multithreaded programs contain two or more threads that can run concurrently. This means that a single program can perform two or more tasks simultaneously. For example, one thread is writing content on a file at the same time another thread is performing spelling check. In Java, the word thread means two...
Read More »

Java Chained Exceptions ~ mkniit

Chained Exception was added to Java in JDK 1.4. This feature allow you to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero. The method will throw only ArithmeticException to the caller. So the caller would not...
Read More »

Java Method Overriding with Exception Handling ~ mkniit

There are few things to remember when overriding a method with exception handling. If super class method does not declare any exception, then sub class overriden method cannot declare checked exception but it can declare unchecked exceptions. Example of Subclass overriden Method declaring Checked Exception import java.io.*; class Super { void show() { System.out.println("parent class"); } } public class Sub extends Super { void show() throws IOException //Compile time error ...
Read More »

Java User made Exception Subclass ~ mkniit

User defined Exception subclass You can also create your own exception sub class simply by extending java Exception class. You can define a constructor for your Exception sub class (not compulsory) and you can override the toString() function to display your customized message on catch. class MyException extends Exception { private int ex; MyException(int a) { ex=a; } public String toString() { return "MyException[" + ex +"] is less than zero"; ...
Read More »

Java throw, throws and finally ~ mkniit

throw keyword is used to throw an exception explicitly. Only object of Throwable class or its sub classes can be thrown. Program execution stops on encountering throw statement, and the closest catch statement is checked for matching type of exception. Syntax : throw ThrowableInstance Creating Instance of Throwable class There are two possible ways to get an instance of class Throwable, Using...
Read More »

Java try with resource statement ~ mkniit

JDK 7 introduces a new version of try statement known as try-with-resources statement. This feature add another way to exception handling with resources management,it is also referred to as automatic resource management. Syntax try(resource-specification) { //use the resource }catch() {...} This try statement contains a paranthesis in which one or more resources is declare. Any object that implements java.lang.AutoCloseable or java.io.Closeable,...
Read More »

Java try and catch block ~ mkniit

Exception Handling Mechanism In java, exception handling is done using five keywords, try catch throw throws finally Exception handling is done by transferring the execution of a program to an appropriate exception handler when exception occur...
Read More »

Java Exception Handling ~ mkniit

Exception Handling is the mechanism to handle runtime malfunctions. We need to handle such exceptions to prevent abrupt termination of program. The term exception means exceptional condition, it is a problem that may arise during the execution of program. A bunch of things can lead to exceptions, including programmer error, hardware failures, files that need to be opened cannot be found, resource exhaustion etc. Exception A Java Exception is an object that describes the exception...
Read More »

Saturday, 13 May 2017

StringBuilder class ~ mkniit

StringBuilder is identical to StringBuffer except for one important difference it is not synchronized, which means it is not thread safe. Its because StringBuilder methods are not synchronised. StringBuilder Constructors StringBuilder ( ), creates an empty StringBuilder and reserves room for 16 characters. StringBuilder ( int size ), create an empty string and takes an integer argument to set capacity of the buffer. StringBuilder ( String str ),...
Read More »

StringBuffer class ~ mkniit

StringBuffer class is used to create a mutable string object. It represents growable and writable character sequence. As we know that String objects are immutable, so if we do a lot of changes with String objects, we will end up with a lot of memory leak. So StringBuffer class is used when we have to make lot of modifications to our string. It is also thread safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors....
Read More »

String class Fucntions ~ mkniit

The following methods are some of the most commonly used methods of String class. charAt() charAt() function returns the character located at the specified index. String str = "studytonight"; System.out.println(str.charAt(2)); Output : u equalsIgnoreCase() equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case doesn't matters with this fuction ). String str = "java"; System.out.println(str.equalsIgnoreCase("JAVA")); Output...
Read More »

Introduction to String ~ mkniit

Introduction to String Handling String is probably the most commonly used class in java library. String class is encapsulated under java.langpackage. In java, every string that you create is actually an object of type String. One important thing to notice about string object is that string objects are immutable that means once a string object is created it cannot be altered. What is an Immutable object? An object whose state cannot be changed after it is created is known...
Read More »

Nested Classes ~ mkniit

A class within another class is known as Nested class. The scope of the nested is bounded by the scope of its enclosing class. ...
Read More »

Interface ~ mkniit

Interface is a pure abstract class.They are syntactically similar to classes, but you cannot create instance of an Interface and their methods are declared without any body. Interface is used to achieve complete abstraction in Java. When you create an interface it defines what a class can do without saying anything about how the class will do it. Syntax : interface interface_name...
Read More »

Abstract class ~ mkniit

If a class contain any abstract method then the class is declared as abstract class. An abstract class is never instantiated. It is used to provide abstraction. Although it does not provide 100% abstraction because it can also have concrete method. Syntax : abstract class class_name { } Abstract method Method that are declared without any body within an abstract class are called abstract method. The method body will be defined by its subclass. Abstract method can never be final...
Read More »

Package ~ mkniit

Package are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration etc. A package can be defined as a group of similar types of classes, interface, enumeration and sub-package. Using package it becomes easier to locate the related classes. Package are categorized into two forms Built-in Package:-Existing Java package for example java.lang, java.util etc. User-defined-package:-...
Read More »

Command line Argument ~ mkniit

Command line argument in Java The command line argument is the argument passed to a program at the time when you run it. To access the command-line argument inside a java program is quite easy, they are stored as string in String array passed to the args parameter of main() method. Example class cmd { public static void main(String[] args) { for(int i=0;i< args.length;i++) { System.out.println(args[i]); } } } Execute this program as...
Read More »

instanceof Operator ~ mkniit

In Java, instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false. Example of instanceOf public class Test { public static void...
Read More »

Monday, 8 May 2017

Runtime Polymorphism ~ mkniit

Runtime Polymorphism or Dynamic method dispatch Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to. In simple words the type of object which it referred...
Read More »

Method Overriding ~ mkniit

When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type. Example of Method Overriding class Animal { public void eat() { System.out.println("Generic Animal eating"); } } class Dog extends Animal { public void eat()...
Read More »

Aggregation ~ mkniit

Aggregation (HAS-A) HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-a relationship with class B, if code in class A has a reference to an instance of class B. Example class Student { String name; Address ad; } Here you can say that Student has-a Addre...
Read More »

Inheritance ~ mkniit

Inheritance (IS-A) Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super...
Read More »