Sunday, June 22, 2014

String in Java

string java | new string java | string in java | java string example | string class methods in java

As most other programming languages, in java string is a sequence of characters. Java implements string as objects of type String. String class is to create string object.

How to create String in Java: -

  1. Implicitly (By string literal) created string in java
  2. Explicitly (By new keyword) created string in java
Implicitly (By string Literal) created string in Java: - When we use double quote, java automatically create a string object. For example:
String s="Hello world";

Explicitly (By new keyword) created string in java: - String create in java, when we use the new operator to instantiate a String object. For example:
String s= new String("Hello world");

Example of String in Java: -
  • Example of Implicitly Creating String in Java

  • Example of Explicitly Creating String in Java

String Class Methods in Java

  1. charAt( ): -It returns the character at the specified index.
  2. compareTo( ): -It compares this String to another Object.
  3. concat( ): -Concatenates the specified string to the end of this string.
  4. equals( ): -It compares this string to the specified object.
  5. endsWith( ): -Tests if this string ends with the specified suffix.
  6. getBytes( ): -Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
  7. getChars( ): -It copies characters from this string into the destination character array.
  8. length( ): -It returns the length of this string.
  9. indexOf( ): -It returns the index within this string of the first occurrence of the specified character.
  10. lastIndexOf( ): -It returns the index within this string of the last occurrence of the specified character.
  11. replace( ): -It returns a new string resulting from replacing all occurrences of old-Character in this string with new-Character.
  12. split( ): -Splits this string around matches of the given regular expression.
  13. substring( ): -It returns a new string that is a substring of this string.
  14. toCharArray( ): -It converts this string to a new character array.
  15. startsWith( ): -Tests if this string starts with the specified prefix.
  16. toLowerCase( ): -It converts all of the characters in this String to lower case using the rules of the default locale.
  17. toUpperCase( ): -It converts all of the characters in this String to upper case using the rules of the default locale.
  18. trim( ): -It returns a copy of the string, with leading and trailing whitespace omitted.
  19. toString( ): -This object (which is already a string!) is returned itself.
  20. replaceAll( ): -It replaces each substring of this string that matches the given regular expression with the given replacement.

Garbage Collection

Garbage collection in java |  java garbage collection | what is garbage collection

Garbage collection is the process or feature of Java, in which Java run time environment automatically destroy the objects created and release their memory when Java run time environment determines that they are no longer needed. And the memory occupied by that object can be released and used by another object.
So we can say that garbage collection in java involves the following activities: -
  • Monitoring the objects and determine when they are not in use
  • Destroy objects that are no longer use and release the resource

How can an object become eligible for garbage Collection: -

An object becomes eligible for garbage collection when the following condition arises: -
  • Nulling a reference: - when an object is to set the reference variable that refers to the object to null.
Example a= new Example();
a= null;
  • Reassigning a reference variable: - when an object is set the reference variable that refer to another object.
Example a= new Example();
Example b= new Example();
a= b;
  • Isolating a reference: - when valid references objects become eligible for garbage collection, because there are no longer use of those objects.

Methods used by Garbage Collector: -

  • finalize() method: - The finalize() method is invoke each time before the object is garbage collected. i.e. the garbage collector gives the opportunity to object to clean up itself. This method is define as following :
protected void finalize()    
{}
                       And this process is called finalization.
  • gc() method: - We can run garbage collector explicitly by calling the gc() method. To run the garbage collector explicitly, we need following mechanism:
    • Create an object of the java run time class as follow:
    Runtime rt= Runtime.getRuntime();
    • Invoke the gc() method
      rt.gc();

Thread life cycle in java

Thread life cycle in java | life cycle of thread in java | java thread life cycle

When we look at the thread life cycle in java it will show, how to create a thread, how to stop a thread, how to java thread sleep and some other stages of thread life cycle in java.
The following figure illustrates the various states that a java thread can be in any point during its life cycle. It also illustrates which method calls cause a transition to other state in the thread life cycle of java. The various states in the thread life cycle in java are: -
  • New
  • Runnable
  • Not Runnable
  • Dead  or Terminate

New Thread: -When we createan instance of the Thread class, the thread enters the new thread state in thread life cycle. The following statement creates a new thread: -
ThreadmyThread = new Thread ();
By this syntax a new thread is created. This new thread is an empty object of the thread class which have no system resources allocated. We have to invoke the start() method to start the thread. The following statement start a thread: -
myThread.start();
Note that when the thread is in the new state, no other method except the start() method can be called, otherwise it throws IllegalThreadStateException.

Runnable Thread: -When we invoke the start() method of a thread, the thread enters the runnable state in thread life cycle. This start() method allocates the system resources to the thread and call its run() method and schedules the thread.
When we talk about single processor system, it is impossible to run all runnable threads in the same time. So the java runtime system must implement a scheduling scheme that shares the processors between all the runnable threads. The thread is in running state when the thread scheduler selects it to be the currently executing process.

Not Runnable: -A thread enters the Not Runnable state when one of the following event occurs in thread life cycle:
  • Invoke java threadsleep() method
  • Invoke java threadwait() method
  • Being blocked
Dead Thread: -A thread can either dead or alive. It can die in two ways: either form natural causes, or by being killed.
A thread die naturally when the loop in the run() method is complete. And we can also kill a thread at any time by calling stop() method. Also note that we cannot restart a dead thread.

Multithreading

Java multithreading | java thread | multithreading in java | java thread example

Threads: -“A thread is defined as the path of execution of a program.” Or we can say that threads is a light weighted process which runs concurrently with other threads. All threads of program defines a separate path of execution.
A process that is made of one thread is known as single threaded process. A process that creates two or more threads is called multithreaded process. Each thread in a multithreaded program runs at the same time and has a different execution path.

Multithreading: - Multithreading is a process of executing multiple thread simultaneously. Multithreading is used to achieve Multitasking.

Multitasking: - Multitasking is the ability to execute more than one task at the same time. Multitasking can be divided into following two categories:
  • Process based Multitasking (Multiprocessing)
  • Thread based Multitasking (Multithreading)
Process based multitasking is the feature of Java which enable to switch from one program to another so quickly that it appears as if the programs are executing at the same time. In Process based multitasking each process have its own address space in memory.
In Thread based multitasking threads share the same address space.

Advantages of Multithreading: -

  • Improved Performance
  • Minimized system resource usage
  • Simultaneous access to multiple applications
  • Program structure simplification

Disadvantages of Multithreading: -

  • Deadlock condition: - when two threads wait for each other to complete their operations before performing their individual action. As a result the two threads become locked.
  • Race condition: -when two or more threads simultaneously access the same variable, and at least one thread tries to write a value in this variable.
  • Lock starvation: - when the execution of a threads is postponed because of its low priority.

Example of Multithreading in JAVA: -

There are two ways to create a thread: -
  • By extending Thread class
  • By implementing Runnable interface
Here we implement the Thread example by using Runnable interface.


Notice how the order changes randomly in the output screen.

Java Package

Java packages | Packages in Java | package java | import package java

“A package is a set of classes that are stored in a directory, which has the same name as the package name. “ Or we can say that Java package is a container, which contain the class file, interfaces etc.
Package enable the way to organize file into different directory according to their functionality and usability. The java package are categorized into following two categories: -
  • Java API (application programming interface) Packages / pre-define packages
  • Java User Define Packages

Java API packages (pre-define): -

The packages that are pre-define in Java language is called java API packages (pre-define packages). The java API consist of various package such as java.utill, java.io, java.lang, java.awt, java.applet etcetera.


Fig: -Hierarchy of the Java Package (pre-define packages)


User Define Java Package: -

The packages that a user creates are called user define packages. These user define packages can be imported in any Java program.

Creating a user define Java package: -We can create a user define java package by using the keyword, package. The package declaration must be at the beginning of the source file. Note that we can make only one package declaration in a source file. We can create a user define package by performing following steps: -
  • First we create a source file which contain the package definition.
  • Create a folder having the same name as package name and save the source file within the folder.
  • Compile the source file.
Now we can use this user define package in any program.


Example of Java Package: -



To Compile  java package: - javac –d c:java MyPack.java


-d option:When we compile the program using –d option, the compiler creates the package directory and move the compiled class file to it.

Note:- c:java is my current working directory, it may be different in your computer.


To Compile: javac UsePack.java

 To Run: java UsePack

Method Overriding

Java method overriding | java override static method | method overriding in java example

“Method Overriding is the concept of Object Oriented Programming in which same name methods are used in different classes (Superclass and Subclass).” Or we can say that, when a subclass inherits methods (with the same name) from a superclass, sometimes it will modify the implementation of a method defined in the superclass called Method Overriding.
Following rules are necessary to achieve Overriding: -
  •   Method must have same name as in super/parent class.
  •   Method must have same parameter as in the super/ parent class.

Example of Overriding in Java: -

Fig: - Example in java
Description: - In the main() method of SubExample class we invoked the display() method, which hides the display() method of class Sup Example and gives the output from display method of SubExample class. This is done by Method Overriding.

Method Overloading

method overloading | java method overloading | overloaded method

Method Overloading is the concept of object oriented programming in which a class having two methods with the same name but different parameter.”
In Java we have two ways to overload the method, one is to by changing the number of arguments and other is to by changing the data type in the time of declare a method. When an overloaded method is invoked, Java matches up the method name and the number and type of arguments to choose which method definition to execute. But remember that Java differentiates overloaded method with the same name, based on the number and type of parameters to that method, not on its return type. So, if you try to create two methods with the same name and same parameter list, but different return types, you’ll get a compiler error.

Example of Method Overloading in Java: -

  • By changing the number of arguments

  • By changing the data type
                                     Figure: -Example of method overloading in Java

Encapsulation in java

encapsulation in Java | what is encapsulation | example of encapsulation

Encapsulation is a concept of object oriented programming which define as a process of wrapping code and the data together into a single unit. Or we can say that “It is the process of binding data members (variables,  properties) and member function (methods) into a single unit”
In Java the basis of encapsulation is the class. When we design a class in Object Oriented Programming (OOPs) like Java, the first thing we should have in mind is encapsulate it. There are several benefits, given below: -
  • Better Maintainability
  • Achieve Data Hiding

Example of Encapsulation in Java:  -

java exampleEncapsulation in java

                                          Figure: -Example of encapsulation in java

JAVA Virtual Machine (JVM)

sun java virtual machine | microsoft java virtual machine | java virtual machine specification

The JVM (java virtual machine) is a platform independent engine use to run java application. Sometime it is called virtual machine which is capable of executing java bytecode. Or we can say that Java Virtual Machine forms a layer between the operating system and the java program. When Java Virtual Machine invoke with a particular class file, the Java Virtual Machine loads the file, goes through a verification process and execute the instruction in that class file.
JVM for different platforms uses different technique to execute the bytecode. The major components of Java Virtual Machine are as follow:
  • Class loader
  • Execution engine
  • JIT (Just In Time) compiler
Class Loader: - The class loader loads the class dynamically, which are required by a program running in the memory.  Java Virtual Machine have following type of class loader: -
  • Primordial class loader: - Primordial class loader loads the Java API (application programming interface) classes required by the running java program.
  • Class loader objects: - Class loader objects loads the classes of the java application program. An application can create class loaders at runtime for loading the classes of the application.
Execution Engine: - Execution engine is the component of the Java Virtual Machine that runs the bytecode one line after another. Different vendors use different technique to implement the execution engine. The java execution engine converts the bytecode to the machine object code and run it.
JIT compiler: - the JIT (Just In Time) compiler is used for compiling the bytecode into executable code. The Java Virtual Machine runs the Just In Time compiler code without interpreting because the Just In Time compiler code is in the machine code format. Running the Just In Time- compiled code is faster than running the interpreted code because it is compiled and does not require to be run, line after line.

Data Types

Java is strongly typed language. This means that every variable must have a declared type. There are two kinds of data types in java: -
  • Primitive Data Types

  • Non-Primitive/reference Type


Primitive Type:-Primitive data type are the data type that are built into the java language. There are eight primitive data types in java programming language, which can be considered in four categories: -
  • Logical – boolean
  • Textual – char
  • Integral – byte, short, int and long
  • Floating Point – double and float

Non-Primitive Type: -Non-Primitive data type are based on Primitive data type and have more functionality that the primitive data type. For ex: - String, Array etc.

Java Access Modifiers

Access Modifiers determine whether other classes can use a particular field or invoke a particular method. Modifiers (Java Access Modifiers) fall into two categories:-
  1. Access Modifiers (public ,protected, private)

  2. Non Access Modifiers (final, abstract)

JAVA Access Modifiers: -

In Java there are following Java access modifiers:-
  • public
  • protected
  • private
  • Default
Public Access: - A class declaration with the public keyword gives all classes in the Java has access to the public class called Public java access modifiers.
Protected Access: - Protected are accessible to the subclasses of the class in which they are declared called Protected java access modifiers.
Private Access: - Only objects of the same class can access a private variable or method called Private java access modifiers.
Default Access: - In Java default/package access control is set when we don't use any of three (public, protected and private) access modifiers called Default Java Access Modifiers.

Access Levels:-

As you can see public access indicates class, package, subclass and world have access to the member.
Protected access indicate class, package and subclass have access to the member but world can't access it.
Private access indicates class have access to the member but package, subclass and world can't access it.
Default access indicates class and package have access to the member but subclass and world can't access it.

Non Access Modifiers:-

  • Final: - Final keyword means the class can't be subclassed. Or we can say that, no other class can ever extend a final class.
  • Abstract: - An Abstract class can never be instantiated.

Polymorphism

Polymorphism is the ability to create a variable, a function, or an object that has more than one form.

Types Of Polymorphism:-

  1. Compile time polymorphism (object is bound with its functionality at compile time) We can achieve compile time polymorphism by using function overloading and operator overloading.  Java does not support compile time binding.
  2. Run time Polymorphism (object is bounded with its functionality at run time) We can achieve runtime polymorphism by using function overriding.

Example of Run Time Polymorphism:-

Output:-
Drive Slowely

Java Constructor

Constructor is a special member function of a class that is used to initialize the object. If a class has a Constructor, Java automatically calls that Constructor when an object is created. The name of the Constructor is the same as the name of the class.

Characteristics of Constructor:-

  • Constructor do not have return type or value.
  • Constructor have same name as class name.
  • Constructor cannot be inherited .
  • java automatically calls the Constructor when an object is created.

Types Of Constructor:-

  1. Simple/default Constructor
  2. Parameterized Constructor

Simple/Default Java Constructor:-


Output:-
Creating Sample

Parameterized Java Constructor:-


Output:-
Creating Sample 0
Creating Sample 1
Creating Sample 2
Creating Sample 3
Creating Sample 4

Interface (Object-Oriented Programming)

Interface (Object Oriented Programming) is a blueprint of a class. They are contract between programmer and programming language.
In Java programming language, an interface is a reference type, similar to a class that can contain only constant, method signatures, and nested type. It is a mechanism to achieve abstraction in Java. There are no method body. Interface cannot be instantiated, they can only be implemented by classes or extended by other interface. One interface can extend and one class can implements more than one interface simultaneously.

Why we Use Interface (Object-Oriented Programming):-

1. Achieve abstraction.
2. Support the functionality of multiple inheritances.

Defining an Interface (Object-Oriented Programming):-

An interface declaration consist of modifiers, the keyword interface, its name, a comma separated list of parent interface (if any), and the its body.

Simple Example of Interface in Java: -

Output:-

Sum is =170
Sub is =30

Abstraction

Abstraction is a process of showing functionality and hiding other internal/implementation details.

Achieving Abstraction via:-

1. Abstract class
2. Interface

Abstract class:-

Abstract class is a class which cannot be instantiated but they can be sub classed. We can declare abstract class by using abstract keyword.
  • Only abstract class can have abstract method (abstract method is a method that is declared without an implementation).
  • We cannot use private and static method in abstract class.
For Ex: - Classes Rectangle, Circle and Line inherit from MyGraphic
Abstract class
Simple Example of Abstract Class:-

AbstractionEvery non abstract subclass of MyGraphic must provide implementations for the draw and resize method:-
Abstraction

Inheritance Oop

Inheritance is a powerful feature of object oriented programming (oop's). It is a  mechanism of sharing attributes and operations among classes. It allows new classes to be derived from existing ones. The derived class (sub class) inherits all the methods and variables of the base class (super class).
In above figure-
  • Class A is the super class of B
  •  Class B is a sub class of A
  • Class B is the super class of C, D and E
  • Class C, D and E are sub class of B

Syntax: -

class Subclass_name extends Superclass_name

     {

          //methods

      }

      

 Example: -

public class SuperObject

  {

    public int length () { ... }

  }

 public class SubObject extends SuperObject

  {

  }  

Types of Inheritance :-

  1. Single Level: - Single sub class is created from a single super class called single level inheritance.
  2. Hierarchical: - More then one sub class are created from a single super class, then that inheritance is called hierarchical inheritance.
  3. Multi Level: - Sub class is created from another Super class, than that inheritance is called as multi level.
  4. Multiple: - Sub class is created from more than one sub class, than that inheritance is called as multiple inheritance.
Note :- Multiple inheritance is not supported in JAVA and Dot Net due to complexity.