Wednesday, December 14, 2016

String Class in Java


String is one of the most used class in java programing language , let see what makes it very useful class in java as well as its properties.



So lets Start with

1) What is String ?

So String is a Class in Java , which is basically the array of characters , In Java String is Class
,not a primitive datatype as in C  language.

Package Name - java.lang.String

2) How can you say that String is immutable in java ?

So we should first understand what is immutable means , So immutable means when any object is not permit itself to be modified or changed. so how string is immutable in java , lets see by example

class StringManupulation

{

 public static void main (String[] args) throws java.lang.Exception

 {

  // your code goes here

  String str1= new String("Program");

  str1.concat("In Java");

          System.out.println(str1);

 }

}

Output :- Program

Logic - As String is immutable it is not allowing the object to be modified as the object initial refer to Program and after concat it with another string , It is not allowing itself to modified


class StringManupulation

{

 public static void main (String[] args) throws java.lang.Exception

 {

  // your code goes here

  String str1= new String("Program");

  str1+=str1.concat("In Java");

          System.out.println(str1);

 }

}

Output : Program In Java

Logic:- As we are changing the reference of the Str1 to Str1+ "In java" Object so the String str1 is now pointing to different object hows valus is "Program In Java".


Difference btw string and string buffer ?

  • String is immutable and StringBuffer is mutable
    • immutable - means the string will not be modify after created
Why String is immutable?
String object are cached in string pool and these strings are shared so changing values has risk.
security reasons-
  • if string is mutable then user could have changed the path after logging.
  • would have changed the db url
  • Mutable string cause problem in reflection also.
Immutability with examples
Non Changing behaviour is called immutability
Example-
String s = new String("programinjava");
s.concat(".com");
System.out.println(s);

Output : programinjava

Second Example:- 

String s1 = new String("programinjava");
String s2= new String ("programinjava");
System.out.println(s1==s2) 
System.out.println(s.equals(s2)) 
Output:

false
true

In String class .equals Method meant for content check
Explanation:-
String s = new String("programinjava");

  •  2 object created , One is in Heap area and other one is in String constant pool ,s is pointing to Heap Object

String s= "programinjava" ;

  • 1 object created in string constant pool
  • Garbage collector is not allowed to access String pool area.

Memory area in java

There are 5 memory area are there in java - 

  1. Heap(garbage collected is applicable only for heap)
  2. Method Area (SCP is in Method area)
  3. Stack
  4. PC Register
  5. Native Method stacks

Whenever we use new operator with string , it will compulsory create object in heap and put it in  Method Area

Example-
How many object will create ?
String s1 = new String("programinjava"); // 1 h 1 scp
String s2 = new String("programinjava");// 1 h , pre scp
String s3="programinjava";// previous scp
String s4 ="programinjava";// previous scp
There are total 3 object;// 2 in heap and 1 in scp

Runtime opertion on string will create object in heap

Examples-
String s = new String("programinjava");
s =s.concat(".com");
Explanation:
Here ,
"programinjava" will be in heap and scp
s.concat will create one string constant in scp ".com"
and create object "programinjava.com" in heap area

NOTE1-For every string constant , one object will be placed in scp area.
NOTE2 - At Runtime if an object is required to placed only in heap area but not in scp area.


Mutable with examples


StringBuffer sb = new StringBuffer("programinjava");
sb.append(".com");
System.out.println(sb);
Output: programinjava.com

StringBuffer sb1 = new StringBuffer("durga");
StringBuffer sb2 = new StringBuffer("durga");
System.out.println(sb1==sb2); //false
System.out.println(sb1.equals(sb2) ); //false

In StringBuffer Class .equals method meant for reference check

If you have any problem in understanding this , Please let me know in Comment section.

Thanks For Reading 
-Noeik



Tuesday, October 18, 2016

Collection in java - Basics

Hello guys , today after almost 1-2 months , I am back with bang ;) , yeah so today i am gonna share my notes about the collection -basics

--------------------------------------------------------------------------------------------------------------------------
Collection
Collection interface
In Array we should know the size at design time
Limation of Array
-Fixed in size
-Homogeneous elements
- No underlying Datastructure

Need of collections
-----------------------
An array is an indexed collectiton of fixed num of homogeneous data elements
-Collections are growable in nature
-Collections can hold both the homogeneous & hetrogeneous Objects
-Implemented with some standard Data structure
-

Diff btw array & collections
-array are fixed in size | collection are growable naturally
-wrt memory arrays are not recommended to use | wrt to memory collections are recommended to use
-wrt performance arrays are recommended to use | collection are not recommended to use
-there is no underlying data structure for arrays and hence ready made method support is not available | every collection class is implemented based on some standard data structure
-array can hold both primitive and objects | collection can only hold objects

What is collection & what is collection framework ?
-Collection is a group of individual objects as a single entity

What is collection framework?
-collection framework defined several class and interfaces .
In Collection framework , there are 9 key interface
1) Collection(I) - 
-It defines the most common methods which are applicable fro an collection object
-In general collection interface is considered as root interface of collection framework.
Note  - There is no conecrete class which implements collection interface directly.

Difference btw collection and collections ?
Collection - interface
Collectitons - Class - its a utility class which define utlitly methods which sorting , seaching.
2) List(T) -(1.2v)

List interface is a child interface of Collection Interface
If we want to represent a group of individual objects as a single entity where duplicates are allowed and insertion order preserved then we use List.
Concrete class of List (I)
-ArrayList(1.2v)
-LinkedList(1.2v)
-Vector(1.0v)
-Stack(1.0v)
Note Vector and stack are legecy classes

3) Set (T) 
Set is a child interface of collection interface
If we want to represent a group of individual objects as a single entity where duplicates are not allowed and insertion order not preserved then we use Set(I)

Concrete class of Set (I)
-HashSet(1.2v)
-LinkedHashSet (1.4v)

** Difference between List and set
Duplicates are allowed | Duplicate are not allowed
Insertion Order preserved | insertion order not preserved

4) SortedSet(I) (1.2v)
interface SortedSet implements Set
SortedSet is a child interface of set
if we want to represent a group of individual objects as a single entity where duplicates are not allowed but all the objects should be inserted according to some sorting order then we use SortedSet

5) NavigableSet(I) (1.6v)
navigable set is a child interface of sortedset
It define several methods for navigation purpose.

6) Queue(I) (1.5v)
it is child interface of collection
if we want to represent a group of individual objects pior to processing then we should go for queue.
ex -before sending a mail all mail ids we have to store somewhere and in which order we saved in the same order mails should be delilvered First in first out for this requirement queue concesp is best choice.
ConcreteC classes
-Prioirity Queue(1.5v)
-Blocking Queue(1.5v)
-LinkedBlockingQueue
-PriorityBlockingqueue
** All the above interface  meant to represent a group of individual objects
** if we want to represent a group of objects as key value pair then we should go for map interface

7) Map(I)(1.2v)

Map is not the child interface of collection
if we want to represent a group of indicula object as key value pair then we use map
Concrete classes
-HashMap -> LinkedHashMap
-WeakHashMap
IndentityHashMap
-Dictonary
-Hashtable
-Properties
8) Sorted Map(I)(1.2v)
it is child interface of map
if we want to represnt a group of key value pairs according to some sorting order of keys then we should go for sortesMai

9) Navigable Map(I)(1.6v)
it is a child interface of SortedMap
define several method of navigable purpose

Concrete Class
-TreeMap (1.2v)

In next post , i will share about the in depth knowledge of ArrayList class.
Hope this post will help you in understanding the basics of Collection interface.

Thanks for Reading
-Noeik

Tuesday, July 5, 2016

Quick Sort Program in java using Array

Hello Guys,
Today after almost 1 month I am posting about Quick Sort.As Quick Sort is much better than merge sort as both of them are of the Complexity of logn but the Constant factor in quick sort is much lesser than merge sort and the quick sort is in place sort algorithm

In my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 

Why Quick Sort is better than merge sort ??

  • The Time Complexity of both is logn but the constant factor of quick sort is much lesser than merge sort
  • Quick Sort is in place algorithm i.e it do not require extra array/linkedlist to sort the list
Java Program of Quick Sort

package com.vp.sort;

public class QsortDemo {
public static void main(String[] args) {
int[] a={10,23,43,2,5,6,12};
quickSort(a,0,a.length-1);
display(a);
}
public static void display(int[] a)
{
String result="[";
for(int sData:a)
{
result+=sData+",";
}
result+="]";
System.out.println(result);
}
public static void quickSort(int[] a,int start, int end)
{
int pivot=0;
if(start<end)
{
pivot = partition(a,start,end);
quickSort(a, start, pivot-1);
quickSort(a, pivot+1, end);
}
}
public static int partition(int[] a , int start , int end )
{
int pivot =a[end];
int i =start;
for(int j=start;j<end;j++)
{
if(a[j]<=pivot)
{
int temp =a[j];
a[j]=a[i];
a[i]=temp;
i++;
}
}
int temp  =a[end];
a[end] =a[i];
a[i] =temp;
display(a);
return i;
}

}

Output-
[10,2,5,6,12,23,43,]
[2,5,6,10,12,23,43,]
[2,5,6,10,12,23,43,]
[2,5,6,10,12,23,43,]
[2,5,6,10,12,23,43,]

Time Complexity - O(logn)

Guys if you are facing any problem in understanding the program do let me know , I will try my best to help you in understanding the program logic

Thank for reading
Noeik


Thursday, June 9, 2016

Factorial Program in Java using recursion

Hi Folks , Today I am going to talk about the factorial program of 'n' numbers in java , how to implement it and what is the time complexity all other things , in my earlier post I have talked about Tower of Hanoi problem 
You can also see other Sorting program
Bubble Sort 
Selection Sort
Insertion Sort 


IMPLEMENTATION OF FACTORIAL 


public class FactorialRecursion {
// main method
public static void main(String[] args) {

System.out.println(factorial(5)); // need to find the factorial of 5
}

public static  int factorial(int i)
{
if(i==0) return 1;
else 
return i*factorial(i-1);
}


}


OUTPUT -   120

Time Complexity - The Time Complexity of Factorial Function is O(n).

Guys if you have any problem regarding the code  and any suggestion , please let me know. I will try to help / Improve.

Thank for reading

- Noeik


Tuesday, May 31, 2016

Stack Implementation program in java

Hi guys , today we are going to learn how to implement stack using array in java. this is one of the most popular java interview question
So lets see how to implement in java using array.

Program 

public class StackOperation {
static int top=-1;
static int[] dataList ;
public static void main(String[] args)
{
// int[] dataList ={10,23,45,5,3,2};
dataList = new int[6];
push(2);
push(3);
push(5);
push(10);
push(23);
push(45);
push(48);
// push(15);
push(3);
pop();
pop();
peek();
}
public static void push(int data )
{
if(top != dataList.length-1)
{
top++;
System.out.println("pushing data "+data);
dataList[top] =data;
}else{
System.out.println("Stack Overflow");
}
}
public static void pop()
{
if(top!=-1)
{
top--;
}else{
System.out.println("Stack Underflow");
}
}
public static void peek()
{
System.out.println(dataList[top]);
}
Hope you guys are able to understand the code if you have any problem , do let me know by comment below.

Thanks for reading

-Noeik

Thursday, May 26, 2016

Tower of Hanoi program in java

Hi Guys , Hope you all are doing well , as we all know that the most populate and most favorite question of interview is Tower of hanoi problem and most of the guy fells that the tower of hanoi program is very much complex.

in my earlier post I have talked about
Bubble Sort 
Selection Sort
Insertion Sort 

So lets see how complex the tower of hanoi program is

Java code of Tower of Hanoi Program 

public class TowerOfHanoi {
public static void main(String[] args) {
move(3 ,'A','C','B');
}
public static void move(int noOfDisc ,char from,char to,char inter)
{
if(noOfDisc==1) System.out.println("Moving Disk "+noOfDisc+" from "+from+" to "+to);
else{
move(noOfDisc-1 ,from, inter,to);
System.out.println("Moving Disk "+noOfDisc+" from "+from+" to "+to);
move (noOfDisc-1,inter,to,from);
// System.out.println("Moving Disk "+noOfDisc+" from "+from+" to "+to);
}
}
Output:-
Moving Disk 1 from A to C
Moving Disk 2 from A to B
Moving Disk 1 from C to B
Moving Disk 3 from A to C
Moving Disk 1 from B to A
Moving Disk 2 from B to C
Moving Disk 1 from A to C

In this program we use the recursion algorithm to calculate the steps required to move the plates from one to another tower.
If you have any problem , do comment below

Thank for reading

-Noeik

Saturday, May 21, 2016

Insertion Sort Program in Java using Array

Hi Everyone ,
In Previous post we have discussed about the Selection Sort its program and  its time complexity, Today we are going to code insertion sort using array list, This is the most popular and most used Sort in all after mert sort.
So lets see the code.

Implementation of Insertion Sort Using Array

/*
 @author noeik
 */
public class InsertionSort {
   
    static int[] data = {10,23,45,5,3,2};// global data integer array
    public static void main(String[] args) {
       
        sort(data);
       
    }
   
    public static void sort(int[] data)
    {
        int j;
        int current;
        for(int i=0;i<data.length;i++)
        {
            current =data[i];
            j=i-1;
            while(j>=0&&data[j]>current)
            {
                data[j+1]=data[j];
                j--;
               
            }
            data[j+1]=current;
            display();
        }
    }
//    displaying the array method
    public static void display()
    {
        String result = "[";
        for(int d :data)
        {
            result = result +d+",";
        }
        result =result+"]";
        System.out.println(result);
    }

}

Output:
[10,23,45,5,3,2,]
[10,23,45,5,3,2,]
[10,23,45,5,3,2,]
[5,10,23,45,3,2,]
[3,5,10,23,45,2,]
[2,3,5,10,23,45,]
[2,3,5,10,23,45,]


Time Complexity:-  The Time Complexity of Insertion Sort is O(n^2)  as there are two loop used.

So Guys hope you all understand the code and if you have any problem just leave comment.
In Next Post , will share the code of Merge Sort.

Thanks for reading 
-Noeik 

Thursday, May 19, 2016

Selection Sort Program Implementation Program in java

Hello Guys ,
In my previous post ,  I discussed about bubble sort program implementation in java using array , Today we will learn the selection sort program implementation in java using array again
So lets get start

Program Implementation of Selection Sort in java 


/*
 @author noeik
 */
public class SelectionSort {
   
    static int[] data = {10,23,45,5,3,2};// global data integer array
    public static void main(String[] args) {
      
        sort(data);
        display();      
    }
//    selection sorting method
    public static void sort(int[] data)
    {
        for(int i=0;i<data.length-1;i++)
        {
            int minIndex =i;
            for(int j=i+1;j<data.length;j++)
            {
                System.out.println("before sorting element");
                display();
                if(data[j]<data[minIndex])
                {
                    int temp =data[j];
                    data[j]=data[minIndex];
                    data[minIndex]=temp;
                    System.out.println("After sorting element");
                    display();
                }
            }
        }
    }
//    displaying the array method
    public static void display()
    {
        String result = "[";
        for(int d :data)
        {
            result = result +d+",";
        }
        result =result+"]";
        System.out.println(result);
    }

}

Output
before sorting element
[10,23,45,5,3,2,]
before sorting element
[10,23,45,5,3,2,]
before sorting element
[10,23,45,5,3,2,]
After sorting element
[5,23,45,10,3,2,]
before sorting element
[5,23,45,10,3,2,]
After sorting element
[3,23,45,10,5,2,]
before sorting element
[3,23,45,10,5,2,]
After sorting element
[2,23,45,10,5,3,]
before sorting element
[2,23,45,10,5,3,]
before sorting element
[2,23,45,10,5,3,]
After sorting element
[2,10,45,23,5,3,]
before sorting element
[2,10,45,23,5,3,]
After sorting element
[2,5,45,23,10,3,]
before sorting element
[2,5,45,23,10,3,]
After sorting element
[2,3,45,23,10,5,]
before sorting element
[2,3,45,23,10,5,]
After sorting element
[2,3,23,45,10,5,]
before sorting element
[2,3,23,45,10,5,]
After sorting element
[2,3,10,45,23,5,]
before sorting element
[2,3,10,45,23,5,]
After sorting element
[2,3,5,45,23,10,]
before sorting element
[2,3,5,45,23,10,]
After sorting element
[2,3,5,23,45,10,]
before sorting element
[2,3,5,23,45,10,]
After sorting element
[2,3,5,10,45,23,]
before sorting element
[2,3,5,10,45,23,]
After sorting element
[2,3,5,10,23,45,]
[2,3,5,10,23,45,]
 
 Time Complexity : The Time Complexity of the Selection Sort Algorithm is O(n^2) ,Because we are using two for loop in the algo.

Hope you guys understand the program well and if you have any problem do comment below.

In next Post I will share the Program of Insertion Sort Using Array.

Thanks for Reading
-Noeik

Bubble Sort using array Program in Java

Hi Guys!!
We know that there are some sorting algorithm in Data Structure under which the easiest one is bubble sort.
so lets see the bubble sort in java using array.


Implementaion of Bubble Sort Using Array

/*
 *
 @author noeik
 *
 */

public class BubbleSort {
   
    static int[] data = {10,23,45,5,3,2};// global data integer array
    public static void main(String[] args) {
       
        sort(data);
        display();   
}
//main sort method
    public static void sort(int[] data)
    {
        for(int i =0;i<data.length-1;i++)
        {
            for(int j=0;j<data.length-1-i;j++)
            {
                if(data[j]>data[j+1])
                {
                    int temp =data[j+1];
                    data[j+1] =data[j];
                    data[j] =temp;
                   
                }
            }
        }
    }
 // display method to show the array
    public static void display()
    {
        String result = "[";
        for(int d :data)
        {
            result = result +d+",";
        }
        result =result+"]";
        System.out.println(result);
    }

}

Output
[2,3,5,10,23,45,] )
Time Complexity:- The Time Complexity of Bubble Sort is O(n^2) because here in program you can see that the code is having 2 loops


In Next Post I will share the program of Selection Sort with its time complexity and all .

Thanks for Reading , Hope you Understand the code and if you have any problem do comment in Comment section below

-Noeik

Monday, May 16, 2016

Installing java 8 in Ubuntu 14.04 LTS

Hi Everyone ,
Most of the Programmers uses Ubuntu Operating System and most of them don't know how to install java in Ubuntu , So this post is regarding with the Installing Java in Ubuntu OS as it is very easy to install java in Windows.

Here are the things you have to do to install java in Ubuntu.

  • Open the Terminal Using CTRL+ALT+T or type terminal in search Launchpad.
  • In terminal you need to first add the ppa repository of webupd8team which is maintaining the Java repository for the Ubuntu OS.
  • update the system repository 
  • install the java 8 installer

    So Run the Below Commands one by one 

    sudo add-apt-repository ppa:webupd8team/java
    sudo apt-get update
    sudo apt-get install oracle-java8-installer 
    To check whether the java installed Successfully run below command
    java -version


    This Confirm whether the Java with version 8 is successfully installed.


    Hope this post will help you guys, If facing any problem feel free to ask your problem I will try to revert back with solution.

Saturday, May 14, 2016

Java Hello World - Program in java

Java is considered as one of the most powerful and popular programming language of all time because of below features.
  • Security
  • Portability
  • Robust 
  • Object Oriented
  • Architecture-neutral and etc
 So Java is the one programming language which programmer can choice for the future career and whenever we talk about coding of any programming language we first code very first code "Hello World " Program

 Here we go .

Code-

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello World");

    }

Where to write the code-
  1. Open notepad (open run and type notepad hit enter)
  2. write the above code and save the file as HelloWorld.java(same as the class name ).
How to Run the Program
  1. open command prompt
  2. navigate to the file where you save the HelloWorld.java file in console.
  3. write below command
    javac HelloWorld.java
  4. The above command will compile the program and create a file HelloWorld.class
  5. now run
    java HelloWorld
    Your Program will run and you will see in console "Hello World"

    This is very basic and beginner's first program in java world.
    Hope you guys will able to understand the program and if you are facing any problem do comment.