Wednesday, December 12, 2012

Multithreading in Java !!!!!


A multiprocessor system can actually do more than one thing at at time but with Java threads, it can appear that you are doing several things simultaneously. Execution can move back and forth between stacks so rapidly that you feel as though all stacks are executing at the same time. 

Thread t = new Thread(r);

Thread is a class in the java.lang package. And this package is imported by default even without package declaration.    A Thread object represents a thread of execution, you will create an instance of class Thread each time you want to start up a new thread of execution.


Three states of new thread


  • When thread is new !

A thread instance has been created but not started. In other words, there is a Thread object but no threa of execution.


  • When thread is in Runnable state !  (t.start();)

When you start the thread, it moves into the runnable state. This means the thread is ready to run and just waiting for its chance to be selected for execution. 


  • When thread is in Running state !
Only the JVM thread scheduler can make that decision. You can sometimes influence that decision but you can not force a thread to move from runnable to running. 


The thread scheduler can move a running thread into blocked state for a variety of reasons. The scheduler will move the thread out of the running state until something becomes available. It can put the thread in sleep by sleep(). You can force the currently running thread to leave the running state and give chance to another  thread to run. In the sleep() method, that's for sure that sleeping thread will not become the currently running thread before the length of sleeping time has expired. 

And how will you apply the sleep() method, that also simple, just write down Thread.sleep(1000); This mean the current thread will not be execute till 1 second. Everything we write down in this method is in milliseconds. 

When you pass a Runnable to a Thread constructor, you are really just giving the Thread a way to get to a run() method. You are giving the Thread its job to do.


___________________________________________

Here I am giving the example of Thread which is taken from Head First Java book for your reference : 

In this example we took two thread and give there name and also set small scenario like what happen if one of the thread sleep or wake up that is runnable and what happen if there is not enough money for them in bank account.



class BankAccount{

private int balance = 100;

public int getBAalance(){
return balance;
}
public void Withdraw (int amount){
balance = balance - amount;
}
}



public class RyanAndMonicaJob implements Runnable {

private BankAccount account = new BankAccount();

public static void main(String[] args) {


RyanAndMonicaJob theJob = new RyanAndMonicaJob();
Thread one = new Thread(theJob);
Thread two = new Thread(theJob);

one.setName("Ryan");
two.setName("Monica");
one.start();
two.start();

}

public void run(){
for(int x = 0; x<10;x++){
makeWithdrawl(10);
if(account.getBAalance() < 0){
System.out.println("Overdrawn!");
}
}
}

private void makeWithdrawl(int amount){

if(account.getBAalance() >=amount){
System.out.println(Thread.currentThread().getName()+" is about to withdrawl.");
try{
System.out.println(Thread.currentThread().getName()+ " is going to sleep.");
Thread.sleep(500);
}catch (InterruptedException ex){ex.printStackTrace();}
System.out.println(Thread.currentThread().getName()+" woke up.");
account.Withdraw(amount);
System.out.println(Thread.currentThread().getName()+" completes the withdrawl.");
}
else{
System.out.println("Sorry,not enough for " + Thread.currentThread().getName());
}
}
}


_____________________________________________

Output:


Ryan is about to withdrawl.
Monica is about to withdrawl.
Ryan is going to sleep.
Monica is going to sleep.
Ryan woke up.
Monica woke up.
Ryan completes the withdrawl.
Monica completes the withdrawl.
Ryan is about to withdrawl.
Monica is about to withdrawl.
Ryan is going to sleep.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Monica is about to withdrawl.
Monica is going to sleep.
Ryan woke up.
Ryan completes the withdrawl.
Ryan is about to withdrawl.
Ryan is going to sleep.
Monica woke up.
Monica completes the withdrawl.
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Sorry,not enough for Monica
Ryan woke up.
Ryan completes the withdrawl.
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!
Sorry,not enough for Ryan
Overdrawn!

_____________________________________________

Monday, December 10, 2012

Understand Wrapper and parse !!!


Practically Wrapper mean wrap the primitive in different value, so that we can use it as per the situation. 

There is wrapper class for every primitive in java. The wrapper class for int is Int, float is Float, char is Character, byte is Byte, double is Double and so on.


                Integer int1 = new Integer("4");
Integer int2 = new Integer("1");
Double int3 = new Double(123.12);

i = int2 + int1;
System.out.println(i);        //5


When we convert the value of wrapped numeric to a primitive than we use following value() methods. That mean we put byteValue(), doubleValue() and so on. 

byte b = int1.byteValue();
System.out.println(b);           

short s = int3.shortValue();
System.out.println(s);

double d = int2.doubleValue();
System.out.println(d);


Following example show the created value of int4 is 5, cause when you convert binary of 101 than you will get 5. So int = 5 now. This is called valueOf() method.

Integer int4 = Integer.valueOf("101",2);
System.out.println(int4);  


Now we look on some parseXxx()  method, it is nearly like valueOf() method.
Following example is for converting string to other primitive what ever you like to apply.


               double d1 = Double.parseDouble("789.456");
System.out.println(d1);


               long l1 = Long.parseLong("101",2);
System.out.println(l1);

Now above example is same like we apply in valueOf() methos, we get same output but using different method.

        

Now when we use toXxxString() method than it convert the following:



                String s1 = Integer.toHexString(123);  
System.out.println(s1);                             // 7b

String s2 = Long.toOctalString(123);
System.out.println(s2);                              //173

String s3 = Double.toHexString(789);
System.out.println(s3);                             //0x1.8a8p9




Now toString(), in this method you can convert every primitive values to string:


               Long l = new Long("789456123");
System.out.println(l.toString());        //789456123

String l2 = Long.toString(789456123);


You can take different primitive value.





Tuesday, December 4, 2012

Understand Abstract class and Interface !!!


Abstract class and Methods



- An Abstract class can not be instantiated but they can be subclassed.

- An Abstract method is method that is declared without an implementation without braces and followed by semicolon.

Example:

public abstract class Animal{

        abstract void eat();

}

- All abstract methods must be implemented in the first concrete subclass    in the inheritance tree. 

- An abstract class can have both abstract and non abstract methods.

- When you don't want a class to be instantiated mark the class with abstract keyword.

- If a class has even one abstract method, the class must be marked abstract.


We have here AnimalObject in above image, might be all three sublcass that is Lion, cat and zebra behave totally different but other thing we find common is eat and roam. You can take advantage of similarities and declare all the animals to inherit from the same abstract object. Lion , Cat and Zebra inherit from Animal.

Example:

public abstract class Animal{
         
         abstract void eat();
         abstract void roam();
}


class Lion extends Animal{

        void eat();{
       void roam();{

}

class Cat extends Animal{

        void eat();{
       void roam();{

}


class Zebra extends Animal{

        void eat();{
       void roam();{

}


Now all this above three non abstract subclass of Animal that is Lion, Cat and Zebra must provide implementation.



Interface 



- An interface is a reference type similar to a class that can certain only constants method signature and nested types. There are no method bodies. 

- Use interface when you want different behavior different classes.

- Interface can not be implemented by class or extended by other interfaces.

- Create an interface using the "interface" keyword instead of class.


Example:

public interface mainInterface extend Interface1, Interface2, Interface3{

               void doSomething (int a, float y);
               int doSomethingElse(String s);


The public access specifier indicates that the interface that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.

An interface can extend other interfaces just as a class can extend or subclass another class. As you know that the class can only extend other class but interface can extend any number of interfaces. And it declare by  comma as shown in above example. 



Thank you for your time..............



Tuesday, November 27, 2012

It is important to know this example that is, How to merge both array in single variable !!!!


Below program provide you the reference regarding merging both array in other ! 

_______________________________________


public class Array {


public static void main(String[] args) {
// TODO Auto-generated method stub

int A [] = {1,2,3,4,5};

int B [] = {6,7,8,9,10};

int C[][] = {A,B}; 


int la = A.length;
int lb = B.length;




System.out.print("ARRAYS in A: ");

for(int x = 0; x<la;x++){
System.out.print("  "+A[x]);
}



System.out.println(" \n");



System.out.print
("ARRAYS in B: ");


for(int y=0;y<lb;y++){
System.out.print(" "+B[y]);
}



System.out.println("\n ");




System.out.print("Arrays in C: ");

for(int i = 0; i<C.length;i++){

for(int j= 0;j<C[i].length;j++){
System.out.print(C[i][j]);
}
     }
}
}
_______________________________________

Output:

ARRAYS in A:   1  2  3  4  5 

ARRAYS in B:  6 7 8 9 10

Arrays in C: 12345678910
________________________________________

In above programme, we use two dimensional array C[] []  to merge the A[] and B[] single array !!!

Hope you enjoy this simple but important programme !

Saturday, November 24, 2012

Apply STACK class in code !!! (java.util.Stack)


Why we use STACK class?

Normally STACK class is not in use that much except in some programme where there is necessary to apply that. In STACK class it use LIFO method that is Last in First Out. For example if you push 1 2 3 4, it will pop like 4 3 2 1. You can see same thing happen in our below code. In STACK we use keyword like 'push' and 'pop', most of you guys know this because same thing we use in couple of algorithms. 'pop' mean removed and 'push' mean inserted, that's very easy. To call this class we write 'import java.util.Stack' in starting of the code.

__________________________________________________


import java.util.Stack;

public class Stack1 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Stack number = new Stack();

for(int x = 10;x>=1;x--){

number.push(new Integer(x));
}

while (!number.empty()){
System.out.print(number.pop());
System.out.print('-');
}
System.out.println("That's enough now !");
}

}
____________________________________________________

Output:

1-2-3-4-5-6-7-8-9-10-That's enough now !
_________________________________________________


In above programme, we start from 10 and till 1 so when it will pop than it is start from correct sequence that is 1 2 3 4 and so on..........

Hope you guys like this.................

If you find this post useful than please share it to your friends..............

Tuesday, November 20, 2012

An example including all STRING METHODS !!!

Meaning of String methods used in this example:

toUpperCase = To make all word capital
toLowerCase = To make all word small
concat = To concatenates both word
trim = To trim the unnecessary space from sentence 
replace = To replace old character to new character
indexOf = Showing position of given character
compareTo = compare with another string
compareToIgnoreCase = compare but also ignore on given condition
equals = compare both string, if it is equal than its true 
equalsIgnoreCase = compare both string and also ignore case of some characters 
______________________________________________

public class Stringexample {

static String firstname = new String ("HARDIK");

static String lastname = new String ("VYAS");


public static void main(String[] args) {
// TODO Auto-generated method stub



int f = firstname.length();
int l = lastname.length();

System.out.println("Showing the length of words: "+f+" "+l);
System.out.println("Calling both from string: "+firstname+ " " + lastname);
System.out.println(" ");

String lcase = firstname.toLowerCase();
String lcase1 = lastname.toLowerCase();

System.out.println("Change it to lower case of spelling: "+lcase+" "+lcase1);

String ucase = lcase.toUpperCase();
String ucase1 = lcase1.toUpperCase();

System.out.println("Change it to upper case of spelling: "+ucase+" "+ucase1);

System.out.println(" ");

String c= firstname.concat(lastname);
System.out.println("Use of concat method: "+c);


String senten = (" GAME  IS  OVER ! ");

String sentence =senten.trim(); 

System.out.println("Trim the unnecessary space from sentence: "+ sentence);
System.out.println(" ");
System.out.println("Using replace method: "+senten.replace(' ', '*'));

System.out.println(" ");
String allname = "john! smith. larry, harry/";

int position = allname.indexOf(',');

System.out.println("Position of any symbol or character that you define in index of method:  "+position); 

String name = "john";
String name2 = "johneeeee";

int compare = name.compareTo(name2);

System.out.println("Comapre method: " +compare);

System.out.println(" ");

        int compar = name2.compareToIgnoreCase(name);  // using below if else condition to give output of this kind of boolean method

if(compar==0){
System.out.println("Both r eqaull");
}else if(compar>0){
System.out.println("name2 is greater than name");
}else{
System.out.println("name is greater than name2");
}

System.out.println(" ");

System.out.println(name2.equals(name)); // this is one of boolean method

System.out.println(name.equalsIgnoreCase(name)); // this boolean method is for ignore same word

}
}
___________________________________________

Outout:


Showing the length of words: 6 4
Calling both from string: HARDIK VYAS

Change it to lower case of spelling: hardik vyas
Change it to upper case of spelling: HARDIK VYAS

Use of concat method: HARDIKVYAS
Trim the unnecessary space from sentence: GAME  IS  OVER !

Using replace method: *GAME**IS**OVER*!*

Position of any symbol or character that you define in index of method:  18
Comapre method: -5

name2 is greater than name

false
true
______________________________________

When you start looking at program than you might be think as confusing that from where to start read it or what ever but when you copy it to your tool than you come to know the real scenario.

When you copy this code and try it your self than and only than you come to know the reason or try to copy the same and do some change it and than write new code so that you can better understand your self confidently. 

I hope that above example will help you a lot,

Thank you for your time..............


Sunday, November 18, 2012

Addition table with help of TWO DIMENSIONAL ARRAY !!!

Here is the program of addition table with help of two dimensional array and you can also create multiplication or subtraction table !  

____________________________________


public class Table {

public static void main(String[] args) {
// TODO Auto-generated method stub

int row = 17, column = 17;

int product[][]= new int [row] [column];

System.out.println("  ");

for(int i = 1; i<row;i++){
for(int j = 0; j< column; j++){

product[i][j] = i +j;

System.out.print(" "+product[i][j]);
}
System.out.println(" ");
}
}
}
_______________________________________

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 
 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 
 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 
 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 
 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 
 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 
 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 
 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 
 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 
 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 
 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 
 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 
 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 
 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 
 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 
_______________________________________________________

Thursday, November 15, 2012

Example of Inheritance and types of Inheritance !!!!

In Java there are four types of Inheritance

1) Single Inheritance (one super class)
2) Multilevel Inheritance (several super class)
3) Hierarchical Inheritance (one super class many sub-classes)
4) Multiple Inheritance   (derived from derived class)


                                   Single Inheritance                             Hierarchical Inheritance
                           Multilevel Inheritance                                 Multiple Inheritance
                                 


________________________________________________

public class Multi {
    int multi1;
    int multi2;
    
    multi(int a, int b){                             // constructor method
        multi1 = a;
        multi2 = b;
    }
    
    int result(){                                        //definition of method
        
      return(multi1 * multi2);
    }

    
    class multi1 extends multi{
        int multi3;
        
        multi1(int a, int b, int c){                       // constructor method

            super(a,b);         // super keyword only used in constructor method
            
multi3 = c;

        }
            int result1(){                                         //definition of method
            return(multi1 * multi2 * multi3);
        }
        }
    


class total{                                          // class with main method
    
    public static void main(String [] args){
        
        multi1 multii = new multi1(1,2,3);         //creating object
        
        System.out.println("Total will be: " +multii.result1());
        
        
    }
}
__________________________________________

Output:

Total will be: 6

________________________________________

Above example is just Single Inheritance example !