Skip to main content

Posts

Showing posts from 2015

Java System Class --- a Utility often used

Java System Class The System class  is a final class and  contains many useful fields and methods which are quite useful utilities like: standard input, output and error, for loading files and libraries. It helps to provide access to externally defined properties and variables. It also contain utility methods to quickly copy an array To get the environment variables. Fields in the System Class: static PrintStream err : The standard error output stream static InputStream in : The standard input stream static PrintStream out: The standard output stream The class has many useful methods , lets see few important methods: static void arraycopy (Object src, int srcPos, Object dest, int destPos, int length): It is used to copy array from src array to destination array starting at srcPosition and starts copying at destPosition and copies the length specified from source to destination. System Properties Methods : It contains method to get , set and clear sys...

Thread -- A Java Class which runs nearly every platform

Thread: Multithreading, Runnable, Thread Class, Callable, DeadLock, Synchronization   Thread is a part of program execution which executes with different set of  variable values . In JVM multiple threads can be running concurrently to server a purpose. When multiple thread executes in program that is called Multi-Threading . Life Cycle Of Thread: Thread could be in 5 states : 1) New 2) Runnable 3) Running 4) Waiting/Blocked 5) Dead/Terminated New : The thread is in new state if you create an instance of Thread class but before the invocation of start() method.     Runnable: The thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. Running: The thread is in running state if the thread scheduler has selected it. Waiting/Blocked: This is the state when the thread is still alive, but is currently not eligible to run. Terminated: A thread is in terminated ...

Refrences Type Java

To understand Garbage collection mechanism we must know about the various reference types for object because on that basis the GC reclaim the memory from the object There are following 4 kinds of reference types in Java:     Strong references.     Weak references.     Soft references.     Phantom references. Strong reference: It is most simple as we use it in day to day programming. if not differently specified then an object is a strong Reference Object Ex String language="English"; A new string object will be created and  a strong reference to it would be stored in the variable 'language'; If any object has a strong reference or it is reachable by any chain of strong reference then JVM will not garbage collect it to avoid any situation where it destroy the object which is currently being worked upon. Weak reference: These are created using WeakReference class which is present in the java.lang.ref . Weak...

Garbage Collector

Garbage Collector : finalize  In C/C++ or all the languages before java we used to manually free the unused memory by deleting the objects/reference created so that system can use that memory for another objects or for other purpose. In java the objects which system can identify as "no longer in use" can be marked as garbage and later recycled. It is also called memory recycling. Most of the object are not used after sometime only few has references further in the program. So java identify those objects which are no longer in use and recycles the memory. So it helps the programmer to relieve the burden of memory management and hence increase the productivity. Garbage collection process mainly handles memory management process, it does not take care about network connection or database connection or any user windows. Those has to be manually managed by programmer. If any of the object is associated with other memory space and before the object is garbage collected an...

Java Exception Handling

Java Exception Handling : try, catch, final An exception is an event which that interrupts the normal flow of program. The exception could occur due to any resource required is not available, user enters invalid data , network connection lost etc. When there is an anomaly during execution of the method, then that method creates an object which contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. The method than pass this object to runtime system which is called throwing an exception. When the exception is handover to runtime system then it tries to find some catch block which can handle this exception.  It tries to find the exception handler block from the method where the exception occurred and proceeds through the call stack in the reverse order in which the methods were called. When it find the block which can handle the type of exception then runtime system passes the exception object to the c...

All about String in Java

String : Immutable, String Pool, String Buffer,  String Builder, String Methods String:  it is basically an Object which represents a sequence of characters .  The Java platform provides the String class to create and manipulate strings. An array of characters works same as java string. For ex: char [] c = {'j','a','v','a'}; String s = new String(s); or simply : String s = "java"; Unlike C and C++ , String does not terminate with null character. The java.lang.String class implements Serializable , Comparable and CharSequence interfaces. String is immutable i.e. it can not be changed once created, on changing new instance is created. To overcome this two more classes are there in java : StringBuffer and StringBuilder. All these are in the same package: java.lang Creating String : We can create string in two ways: 1) String literal 2) Using new keyword String literal :  Java String literal is created by using double quotes....

OBJECT class in Java

OBJECT class in Java : Object is at the top of class hierarchy in java. Every class in the Java system is a descendent (direct or indirect) of the Object class. The Object class defines the basic state and behavior that all objects must have, such as the ability to compare oneself to another object, to convert to a string, to wait on a condition variable, to notify other objects that a condition variable has changed, and to return the object's class. Mainly below methods are provided by Object class : public String toString() returns the string representation of this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public boolean equals(Object obj) compares the given object to this object. public int hashCode() returns the hashcode number for this object. public final Class getClass() returns the Class class object of this object. The Class class can further be used to get the metadata of ...

Abstract Class & Interface

Abstract Class & Interface Abstract Class:   Abstract class is same as other class except that it can not be instantiated . It is generally to write the common functionality in the parent class. It can have abstract and non-abstract method. Abstract class can have final, non-final, static and non-static variables. It can also implement interface and define the methods of interface, but it can not be instantiated. Interface:   An interface in java is a blueprint of a class. It has static constants and abstract methods only. Interface basically defines the contract for a class to implement. It is a mechanism to achieve fully abstraction. There can be only abstract methods in the java interface not method body. It cannot be instantiated like abstract class. A class can extend multiple Interfaces. An interface can extend multiple Interfaces. Abstract class Interface 1) Abstract class can have abstract and non-abstract methods. Interface can have only abst...

Nested Classes

Nested Classes   The Java programming language allows you to define a class within another class. Such a class is called a nested class. Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes .  Non-static nested classes are called inner classes .   class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } } A nested class is a member of its enclosing class.  Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.  Static nested classes do not have access to other members of the enclosing class. As a member of the OuterClass , a nested class can be declared private , public , protected ,  or package private .  Local Class Local classes in Java are like inner classes (non-static nested classes) that are defi...

Overloading & Overriding in Java

Overloading & Overriding   in Java Overloading 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 different signatures, then the method name is said to be overloaded. This fact causes no difficulty and never of itself results in a compile-time error. There is no required relationship between the return types or between the throws clauses of two methods with the same name but different signatures. Overriding If more than one method declaration is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen. The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error...
Composition vs Inheritance Composition :  Composition, simply mean using instance variables that are references to other objects. For example: class A {     //... } class B {     private A objA = new A();     //... } Composition is a "has-a" relation. Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need. Two fundamental ways to relate classes are inheritance and composition . Although the compiler and Java virtual machine (JVM) will do a lot of work for you when you use inheritance, you can also get at the functionality of inheritance when you use composition.  There are different views which favors COMPOSITION over Inheritance: One example could be : java.util.Stack inherits java.util.Vector . Stack is not a type of Vector, it should not be allowing random access, arbitrary insertion or deletion . It could have been compositio...

Inheritance in Java

Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. It is ' is-a' relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used.  Class Inheritance in java mechanism is used to build new classes from existing classes. When a Class extends another class it inherits all non-private members including fields and methods The main purpose is to promote the reuse of code.  The inheritance relationship is transitive: class A extends class B which extends class C. So class A will inherit class C also. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass. The java.lang.Object is top of any Class inheritance hierarchy.  Types of Inheritance in java: Single Inheritance  : When a class inherit just one top class example : class A exte...

Important Keywords: Final and Abstract:

Important Keywords: Final and Abstract: Final:  'final' keyword in java is used to restrict the user. It is applied to  'class' 'method' 'variable'     a final class cannot be extended     a final method cannot be overridden     final fields, parameters, and local variables cannot change their value once set *  a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. Example: class FinalExample{    // blank final variable    static final int Request_Number;    static{       Request_Number=4532134;    }    public static void main(String args[]){       System.out.println(Example.Request_Number;);    } ...

Important Keywords: Static, Continue,Break:

Important Keywords: Static, Continue,Break:  Static: The static keyword in java is used for memory management mainly.  The static keyword members belongs to the class rather than instance of the class. Following members can be declared as static: variable (also known as class variable) method (also known as class method) block nested class  static variables : We can use static keyword with a class level variable. A static variable is a class variable and doesn’t belong to Object/instance of the class. Since static variables are shared across all the instances of Object, they are not thread safe . Usually static variables are used with final keyword for common resources or constants that can be used by all the objects. If the static variable is not private, we can access it as: ClassName.variableName //static variable example private static int a ge; public static String name; static methods: A static method belongs t...

Java Access Modifiers – public, protected, private and default

J ava Access Modifiers – public, protected, private and default The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a class can control what information or data can be accessible by other classes. To take advantage of encapsulation, you should minimize access whenever possible. A Class can only be default of public If a class does not have any access modifier before it, it means it has default access i.e. it can be accessed only from other classes in the same package. If a modifier for class is public it means it can be accessed anywhere.  But we can have only public class in a single source file and the name of the file should be same as public class name. There are 4 types of java access modifiers: private protected default public Private : Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. The private (most res...

Java Variables: Local, Instance and Static, Parameter

Java Variables: Local, Instance and Static, Parameter A variable is a named storage that our programs can manipulate . Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. You must declare all variables before they can be used. There are four kinds of variables in Java: *Local variables *Object/Instance variables *Class/static variables These are variable types are different according to their different scope of visibility.   Local Variables: Local variables are declared in methods, constructors, or blocks. The scope of the local variables is withing that only i.e. local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block. There is no default value for local variables so local variables ...

Java Data Types: Primitive, Reference

Java Data Types: Primitive, Reference Primitive:   A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:   * byte, short, int, long, float, double, boolean, char In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string"; . String objects are immutable , which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such A reference type is a data type that’s based on a class ...

OOPs Principles : Inheritance, Polymorphism, Abstraction,Encapsulation

Inheritance, Polymorphism, Abstraction,Encapsulation  Object means a real word entity such as Name, Car, table etc.  Object-Oriented Programming is a method  to design a program using classes and objects.  It simplifies the software development and maintenance by using below concepts: Object Class Inheritance Polymorphism Abstraction Encapsulation Object An object is a software bundle of related state and behavior. Objects are made up of attributes and methods. Attributes are the characteristics that define an object; the values contained in attributes differentiate objects of the same class from one another. Class "Collection of objects " is called class. It is a logical entity. It models the state and behavior of a real-world object. * Every class, except Object , has one and only one immediate superclass * An object "knows" what class it belongs to, and can use class data and class methods, but a class   does not "kno...

Java Concepts

BASIC JAVA Inheritance, Polymorphism, Abstraction,Encapsulation Java Data Types: Primitive, Reference Java Variables: Local, Instance and Static Java Access Modifiers – public, protected, private and default     Important Keywords: Static, Continue,Break , Final,Abstract Inheritance in Java Composition vs Inheritance   Overloading & Overriding   Nested Class in Java Abstract Class & Interface OBJECT class in Java String : Immutable, String Pool, String Buffer,  String Builder, String Methods Java Exception Handling : try, catch, final Garbage Collector : finalize  Reference type in Java Thread: Multithreading, Runnable, Thread Class, DeadLock, Synchronization Java System Class Java IO : File Creation, Open, access,Write,append, InputStream,append, Downloading a file, Scanner Class, Processing CSV