MY mENU


Thursday 31 January 2013

Strings in Java


In java.lang package we have below three classes to handle strings
  • String
  • StringBuffer
  • StringBuilder--- introduced in java 5, as non-thread safe class.
  1. These three are subclasses of CharSequence interface.
  2. All these three classes are final classes.
  3. These are subclasses of java.io.Serializable interface,
  4. String class is a sub class of comparable interface, but StringBuffer and StringBuilder are not.

String is immutable where as StringBuffer is mutable. Strings are constant their values cannot be changed in the same memory after they are created, so string is defined as an immutable sequence of characters.

String class is given when char array is available to represent sequence of characters because of its given to store characters dynamically without size limitation.

The possible ways to create String Object:
  • By assigning string literal directly   --- String s=”abc”;
  • By using any one of the string class constructors.

String class Constructors:
  • String(), no null string object
  • String(String value)
  • String(StringBuffer sb)
  • String(StringBuilder sb)
  • String(char[] ch)
  • String(char[] ch, int offset, int count)
  • String(byte[] ch)
  • String(byte[] ch, int offset, int count)

We should not pass null to create string object using any one of the above constructors it leads to RE: java.lang.NullPointerException

We can create null string referenced variable like string str=null;

But we cannot create String object with null, it leads NPE, like String str=new String(null);

What is the difference between creating String objects using constructor and by assigning literal?
String Pooling means pooling strings, it means grouping string objects. If we create String objects by assigning same string literal, only one object is created and all referenced variables are initialized with that same String object reference. Then all referenced variables are pointing to same String object. This is the another reason why String object become immutable.

Why because, if we change that String value using one referenced variable, if that modification is stored in same memory, other referenced variables are also affected. To solve this problem SUN decided to create String as immutable.

This string pooling concept is not applicable for the String objects those are created using “new and constructor”, all string objects created by using constructor will have separate object.

  • String is an immutable sequence of characters.
  • StringBuffer is a mutable sequence of characters.
  • StringBuilder is also mutable sequence of characters.
  • StringBuffer object is thread-safe; it means its object is not modified by multiple threads concurrently, because all its methods are declared as “Synchronized”.
  • StringBuilder as a non-thread-safe class means all its methods are non-synchronized methods.

So in single thread model application we must use StringBuilder, so that object locking and unlocking will not be there, hence performance is increased. In single thread model application operations are executed in sequence hence there is no chance StringBuffer or StringBuilder.

  • If we do not want to store string modifications in the same memory, we must choose string.
  • To modifications in the same memory, we must choose StringBuffer or StringBuilder.

Advantage and Disadvantage in String:
Since modifications are preservating in another memory location, we will have both original and modified values.

Disadvantage is it consumes lot memory for every operation, as it stored it modifications in new memory. So it leads to performance issue.

To solve this performance issue,  in projects developers store data using StringBuilder. After all modifications they convert SB into String and then pass it back to user.

Advantages in StringBuffer and StringBuilders are given high performance because consumes less memory as all modifications are stored in same memory. Disadvantage is original value will not be preserved.

StringBuffer Operations :
  • Append
  • Insert
  • Delete
  • Reverse

We cannot perform these operations on String.

Using String object we can concat new string to the current string in two ways.
  • Using “+” operator
  • Using concat() operator.
Using StringBuffer object we can concat new string to the current string only in one way.
  • Using append() method.

Due to concatenation operation by using concat() method, if current string object is modified, JVM creates new object and returns that object reference. If it is not modified it returns the same current object reference.
But when we use + operator whether current string object is modified or not modified JVM always creates new String Object.

The append() operation performed on StringBuffer , it always stores modification in same memory and returns the same SB object reference.

  • Concatenation means appending given string to current string in difference memory.
  • Appending means appending given string to current string in same memory.

Using equals() method String objects are compared with state, because it is overridden in this class. Also hashcode method is override to satisfy equals method contract.

But in StringBuffer and StringBuilder classes equals() method is not overridden, so using equals() method their objects are compared with reference.

In all three class toString() method is overridden to print the object state.

StringBuffer has default capacity 16 buffers. It increases its capacity automatically when size reached capacity.

  • Using String(StringBuffer) constructor and StringBuffer.toString() we can convert StringBUffer to string.
  • Using StringBuffer(String) constructor we can convert String to StringBuffer.

What is the best design in defining a method to take and return string data as argument?
The parameter and return type should be java.lang.String, not StringBuffer.
The problem if we take StringBuffer as parameter or return type is: user should convert that string data as StringBuffer object, because StringBuffer will not accept string data directly.





Wednesday 30 January 2013

Equals() Method


Using “==” operator – it always compares objects with their referecnces.
Using “equals” method- it compares objects based on its implementation.

Why equals() method is specially given when == operator is already doing the objects comparison operation?
  • == operator will only compare reference of the objects.
  • Real world objects must be compared with their state.
  • For this purpose == operator should be overloaded.
  • Since java does not support operator overloading.
  • We need an alternative to == operator.
  • Hence equals() method is given by sun to provide.
  • object state comparison logic” by developer if need as per project requirement.
  • And every object may not contain state.

Object class developer does not know the sub class required object state comparison logic.

Hence it is the sub class developer’s responsibility to override equals() to compare subclass objects with their state.

If equals() method is overridden then hashCode() method must be overridden with below contract:

If equals() method return true by comparing two objects, then hashCode of the both objects must be same.

If it returns false, the hashCode() of the both objects may or may not be same.

Object Class


The object class is the root class of  the class hierarchy.

Why object class is the super class for all java classes?

Because of below 2 reasons object class is made as super class for every class.
Reusability: every object has 11 common properties. These properties must be implemented by every class developer. So to reduce burden on developer SUN developed a class called object by implementing all these 11 properties with 11 methods. All these 11 methods have generic logic common for all subclasses. If this logic is not satisfying subclass requirement then subclass can override it.

To achieve runtime polymorphism: so that we can write single method to receicve and send any type of class object as argument and as return type.

What are the common functionalities of every class object?

1. Comparing two objects:
Public Boolean equals(Object obj)

2. Retrieving hashcode(object identity)
Public native int hashCode()

3. Retrieving the runtime class object reference:
Public final native Class getClass()

4. Retrieving object information in String format for printing purpose:
Public String toString()

5. Cloning Object:
Protected native Object clone() throws CloneNotSupportException

6. Executing object clean-up code/ resource releasing code:
Protected void finalize() throws Throwalbe

7.8,9: Releasing object lock and sending thread to waiting state:
Public final void wait() throws InterruptedException
Public final native void wait(long millis) throws InterruptedException
Public final void wait(long millis,int nanos) throws InterruptedException

10,11:.Notify about object lock availability to waiting threads:
Public final native void notify()
Public final native void notifyAll()

All above operations are implemented with generic logic that is common for all objects, so that developer can avoid implementing these operation in every class, also SUN can ensure that all the operations are overridden by developers with the same method prototype. This feature will provide runtime polymorphism.

Developer should override these methods with object state.

We can override below five methods:
  1. Equals
  2. hashCode
  3. toString
  4. clone
  5. finalize


sun recommended to override equals,hashCode,toString method in all classes.


Tuesday 29 January 2013

Oracle InterViewQusetions 11-15

11. what is null value?
Null Value is neither zero nor it is a blank space. It is some unknown value which occupies 4 bytes of space of memory in SQL.

12. Define transaction?
A transaction is a sequence of SQL statements that Oracle Database treats as a single unit.

13. what is the difference between sql&oracle?
SQL is Stuctured Query Language.Oracle is a Database.SQL is used to write queries against Oracle DB.

14. What are different Oracle database objects?
TABLES
VIEWS
INDEXES
SYNONYMS
SEQUENCES
TABLESPACES

15. What is hash cluster?
A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.

Oracle InterView Questions 6-10

6. What is the difference between clustered and a non-clustered index?
A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.
A Non clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk.

7. What is a Table-space?
A database is divided into Logical Storage Unit called tablespace. A tablespace is used to grouped related logical structures together.

8. Why use materialized view instead of a table?
Materialized views are basically used to increase query performance since it contains results of a query. They should be used for reporting instead of a table for a faster execution.

9. What does ROLLBACK do?
ROLLBACK retracts any of the changes resulting from the SQL statements in the transaction.

10. Compare and contrast TRUNCATE and DELETE for a table?
Both the truncate and delete command have the desired outcome of getting rid of all the rows in a table. The difference between the two is that the truncate command is a DDL operation and just moves the high water mark and produces a now rollback. The delete command, on the other hand, is a DML operation, which will produce a rollback and thus take longer to complete.

Oracle InterView Questions

1.what is Oracle Table?
A table is the basic unit of data storage in an Oracle database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

2. What are Clusters?
Clusters are groups of one or more tables physically stores together to share common columns and are often used together.

3. What is an Index?
An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

4. What are the advantages of views?

  • Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
  • Hide data complexity.
  • Simplify commands for the user.
  • Present the data in a different perspective from that of the base table
  • Store complex queries.

5. What are the various types of queries?
The types of queries are :

  • Normal Queries
  • Sub Queries
  • Co-related queries
  • Nested queries
  • Compound queries






Monday 28 January 2013

OOPS Concept


1. Encapsulation: the process of hiding internal data from the outside world; and accessing it only through publicly exposed methods is known as data encapsulation.
It means restricting direct access of class variables to outside class members and providing accessibility to those variables through public methods is called encapsulation.
In java encapsulation can be implemented. Ultimately through encapsulation we are hiding implementation details from user.
By declaring variables as private, to restrict direct access, and
By declaring one pair of public setter and getter methods to give access private variables.

2. Inheritance: the process of reusing class members from another class as if it were defined in that class is called inheritance. It can also be defined as it is a process of obtaining one object property to another object.
As the name suggests, inheritance means to take something that is already made. It is the concept that is used for reusability purpose.
Inheritance can be implemented in java by using below two keywords:
  • Extends
  • Implements

Extends” is used for developing inheritance between two classes or two interfaces, and “

"implements” keyword is used to developed inheritance between interface, class.

Class sample extends example{}

The class followed by extends keyword is called super class/base class, here example is super class, and the class that follows extends keyword is called subclass/derived class, here sample is sub class.

Basically by implementing inheritance we are establishing a relation between two classes and then extending one class scope to another class.

When subclass is loaded its entire super classes are loaded, and also when subclass object is created all its super class non-static variables memory is created. Invoked method is executed from  sub class.

Super class is loaded using extends keyword.

Super class object is created by calling super class constructor from sub class constructor using super() method.

Super() method is used to call super class constructor from sub class constructor to initialize super class non-static variables when subclass object is created. Compiler places super() method call in all constructors at the time of compilation if there is no super() or this() method call is placed explicitly.

Invoked super class constructor means not create an object of it, it means super class non static variables gets memory in subclass object region.

We can initialize super class non-static variables by using parameterized constructor so we must place “super” call explicitly with argument. The argument type should be the constructor parameter type.

Inheritance can only be implemented if super calss has a visible constructor. It means other than private constructor.

Empty Super Class:
    Class Example{}
             Class Sample extends Example{}

Super class with Explicit no-arg constructor::
Class Example{
Example (){}
}
             Class Sample extends Example{}

Super class with Explicit parameterized constructor::
Class Example{
Example (int a){}
}
             Class Sample extends Example{}

Super and sub class with Explicit parameterized constructor::
Class Example{
Example (int a){}
}
             Class Sample extends Example{
Sample(int b){}
}

Super is used to access the members of the super class. To access the hidden data variables of the super class hidden by the sub class. Super keyword is most useful to handle situations where the local members of a subclass hide the members of a super class having the same name.

Hence super keyword can be defined as “it’s a non-static variable used to store super class non-static member’s memory reference through current sub class object for separating super class members from subclass members”.

When we must define subclass for a class?
Sub classes must be written only if we want to extend the functionality of the existed class. To treat the new class as existed class type, for implementing runtime polymorphism.

What are the benefits of inheritance?
one of the key benefits of inheritance is to minimize the amount of duplicate code in an application by sharing common code amongst several subclasses. Where equivalent code exists in two related classes, the hierarchy can usually be refractored to move the common code up to a mutual super class. This also tends to result in a better organization of code and smaller, simpler compilation units.

Inheritance can also make application code more flexible to change because classes that inherit from a common super class can be used interchangeably. If the return type of a method is super class then the application can be adapted to return any class that is descend from that super class.

3. Polymorphism: having multiple forms of a method with same name is called polymorphism. The meaning of polymorphism is something like one name, many forms. One name may refers to different methods. We can develop polymorphism is using below concept.
Method overriding
Method overloading

Types of polymorphisms:

Compile-time polymorphism: when a method is invoked, if its method definition which is bind at compilation time by compiler and only executed by JVM at runtime, than it is called compile-time or static binding. Method overloading is the best example.

Run-time polymorphism: when a method is invoked, if its method definition which is bind at compilation time and is not executed by JVM at runtime, instead if it is executed from the subclass based on the object stored in the reference variable is called runtime polymorphism. It can only be implemented through method overriding and up-casting.
Run-time polymorphism not only provides automatic garbage collection it also allows you to change the behavior of a class without changing even a single line of code in a class. Hence we can say runtime polymorphism based application provides pluggability nature and means loose coupling.

What is meant by loose coupling and tight coupling?
If a product is functioning correctly even after changing one of its parts with another company given party, it is called loosely coupled way of manufacturing. Else it is called tightly coupled way of manufacturing.

4. Abstraction: the process of removing or hiding unnecessary information is called abstraction. The process of providing necessary method prototype by removing/ hiding unnecessary method logic/ body is called abstraction. Here unnecessary details mean method body and logic. It only provides us method prototypes and hides method implementation details.
Hiding non essential details can be developed using concrete methods.
Removing non essential details can be developed using abstract methods.

How can you force subclass to override super class method?
By creating method as abstract method

Procedure to create abstract methods in a class:
Create a method without body. A method created without  body is called abstract method. Rule of abstract method is it should contain abstract keyword and should ends with semicolon.
Abstract void m1();

Why method should has abstract keyword if it does not have body?
In a class we are allowed only to define methods with body. Since we are changing its default property- means removing its body- it must has abstract keyword in its prototype.
If method does not have body it should be declared as abstract using abstract modifier keyword else leads to CE:

If a class have abstract method, it should be declared as abstract class using abstract keyword else it leads to CE:

If a class is declared as abstract it cannot be instantiated violation to CE:

Why abstract class cannot be instantiated?
Because it’s abstract method cannot be executed. If compiler allows us to create object for abstract class, we can invoke abstract method using that object which cannot be executed by JVM at runtime. Hence to restrict calling abstract methods compiler does not allow us to instantiate abstract class.

We are not allowed to declare abstract method as static. It leads to compiler time error illegal combination of modifiers abstract and static.

Only three modifiers allowed with abstract they are:
Native, protected, public.

In projects development we come across three types of persons:

Service specifier—the person or company who develops specification is called service specifier.

Service provider—the person or company who implements specification is called service 
provider.

Service user—who uses the specification, further its implementation is called service user.

What we achieve via abstraction in java?
By implementing abstraction we can develop contract document between service providers, service users. This contract document is called specification, developed using interface in java.
This specification is defined by a common company with all abstract methods.
Specification provides the below information to both service provider and service user.

Why projects development is starts with interfaces?
To develop loosely coupled based  applications runtime polymorphism applications.
Loosely coupled or runtime polymorphism based application means it allows to replace an object with another object  of same category without recompiling and it exhibits the same expected functionality.

Saturday 26 January 2013

What does the assert keyword do in Java?


assert is a keyword added in Java version 1.4.
assert tests the programmer's assumption during development without writing exception handlers for an exception. Suppose you assumed that a number passed into a method will always be positive. While testing and debugging, you want to validate your assumption. Without the assert keyword, you will write a method like: 

private void method(int a) { 

if (a >= 0) {
// do something that depends on a not being negative
} else {
// tell the user that a is negative
}

This is simple exception handling; consider the case of big one. Assertion will come into the picture when you don't want to take the time to write the exception handling code.
Consider the above program with assertion:

private void method(int a) {
assert (a>=0); //throws an assertion error if a is negative.
// do stuff, knowing that a is not negative
}

In this program, assert (a>0) will pass when 'a' is only positive. Isn't this much cleaner than the previous example? If the value of 'a' is negative, then an AssertionError will be thrown.
There are two types of assertions: 
  1. Simple
  2. Really simple
Example of a really simple assertion:

private void method() {
assert (x>0);
//do more stuff
}

Example for simple assertion: 
private void method() {
assert (x>0) : "X is" + x ;
// do more stuff
}
The difference between these two is that the simple assertion - the second example - appends the expression after the colon to the error description in the stack trace.
Note: assertion code - in effect - evaporates when the program is deployed.

For assertion first you need to invoke the assertion.
Asserts are disabled by default in the JVM. In order to run a program with asserts you must use the -ea command line parameter (i.e. java -ea AssertTest).
 
Even though your compiler suggested it was using java version 1.4, it wasn't actually because you compiled using the "javac [files]" command instead of the "javac -source 1.4 [files]" command. Assertions only work in version 1.4 and later versions.
 
When you are using assert keyword, you have to enable it. Otherwise it wont give any result. 
java -enableassertions classfile

Final method and Final class


Final method: a method which has final keyword in its definition is called final method.

When a method should be defined as final?

If we do not want allow subclass to override super class method and to ensure that all sub classes uses the same super class method logic then that method should be declare as final method.

Final method cannot be overridden in subclass, violation leads to CE:

What is the difference between private and final methods?

Private method is not inherited, where as final method is inherited but cannot be overridden.

Can we overload final method in subclass?
Yes, we can overload final method in subclass.

Class Ex {
Final void m1 (int x) { }
}

Class Sa extends Ex{
Void m1(){}
}

Final Class:

A class which has final keyword in its definition is called final class.

When a class should be defined  as final?
In the below situations we must define class as final
  1. If we do not want define all methods as final
  2. If we do not want allow subclasses to extend our class functionality.

Sub class cannot be defined from final class, violation leads to CE:

Final class Ex{
}

Final class members are not final until they are declared as final members explicitly using final keyword.

Friday 25 January 2013

Methods in Java


Method: method is a block of a class that contains logic of that class. Logic must be placed only inside a method, not directly at class level. If we place logic at class level compiler throws error.

Method Prototype: the head portion of the method is called method prototype.

Method body and logic: the “{}” region is called method body, and the statements placed inside method body is called logic.

Method parameters and arguments: the variables declared in method parenthesis “( )” are called parameters. We can define method with ZERO to ‘n’ number of parameters.
The values passing to those parameters are called arguments. In method invocation we must pass arguments according to method parameters order and type.

Ex: void add (int a, float b) {  }     //here int a, float b are method parameters
Add (50, 60.5);   // here 50, 60.5 are arguments.

Method Signature: the combination of [Method name+parameters list] is called method signature.

Ex: void add (int a, int b) { }   // here add (int a, int b) is the method signature.

Method Return type: the keyword that is placed before method name is called method return type. It tells to compiler and JVM about the type of the value is returned from this method after its execution.

Void return type keyword: if we do not want to return any value a method, we must use “void” as return type. It tells that the method does not return any value. If we want to return any value a method, we must place data type keyword as return type.

Main method terminology with all above parts:

Public static void main (String[] args)

Public -- Accessibility modifier
Static----Modifier
Void----Return Type
Main----Method Name
String [ ]----Parameter Type
Args------Parameter Name

The process of creating method with body is called method definition. This method is called Concrete Method.

Ex: public static void add(int a, int b){
System.out.println(a+b);
}

The process of creating method without body is called declaring a method/ method declaration. This method is called also abstract method. In method declaration the modifier “abstract” is mandatory and also should be terminated with “;”.

Ex: public native abstract void add(int a, int b);

  •  When we call a method control send to that method.
  •  If we pass argument that value is stored in parameter variable.
  • After method execution that parameter variable is destroyed and control is sent back to calling method.
  •   Control is sent back to calling method with value if method has return type is not void.


    Types of Methods: Basically concrete methods are divided into 3 types:
       Based on static modifier we have two types of methods
  •  Static methods
  •  Non-static methods

We can call static methods directly from main method, but we cannot call non-static methods directly from main method. It leads CE:”non-static method cannot be referenced from static context”, because class level members will not get memory directly. JVM provides memory only if we use either “static or new” keywords.

Main method has static keyword in its prototype since it is the initial point of class login execution; it must be identified and gets memory directly by JVM. Hence it has static keyword in its definition. Of course it must be called without object creation.

class MethodStatic
{          static void m1(){
                                System.out.println("in M1()");
                }
                void m2(){
                                System.out.println("M2() method");
                }
                public static void main(String[] args)
                {
                                System.out.println("Hello World! this is main Method");
                                m1();
                                MethodStatic ms=new MethodStatic();
                                ms.m2(); //it gets memory with reference to “ms” variable.
                }  }

2.  Based on return type we have two types of methods
  •  Void methods
  •  Non-void methods

In void methods statements are optional, but in non-void methods return statement is mandatory with value range less than or equals to method return type range.
If we do not place return statement in non-void methods compiler throws CE: “missing return statement”

Types of return statements:  return is only allowed in void method and constructor, and it is optional.

 Return is only allowed in non-void methods, and it is mandatory.

Basically return statement is used to terminate method execution and for sending control back to calling method.

In general, void methods are called in three ways 1. Directly—m1(); 2. As variable initialization statement—int x=m1();; 3.As SOPLN() argument—Sopln(m1());

The non-void methods can be called in all three ways.  In the first way the return value is lost. In the second way the returned value is stored in the destination variable. In the third way the returned value is printed on console.

3Based on parameter we have two types of methods
  •          Parameterized methods
  •          Non-parameterized methods


Wednesday 23 January 2013

Why OOPs?

  • OOPs stands for “Object Orient Programming System”. It’s a technique not technology.
  • It means, it does not provide any syntaxes or API’s, instead it provides suggessitions to design and develop objects in programming language.
  • This technique is introduced to represent real world object in programming languages, the objects such as person, Animal, Shape, Vehicle, etx… and further to achieve security and to communicate with other programming languages, such as C,C++,.NET,PHP,HTML,JAVA etc… with proper connectors.
  • All living and non-living things are considered as object.
  •  If we developed project according to real world object behavior we will get many advantages.
Definition of OOPs:
  • OOP is an approach that provides a way of modularizing a program by creating partitioned memory area for both data and methods that can be used as template for creating copies of such modules on demand.
  • Unlike procedural programming, here in the OOP programming model, programs are organized around objects and data rather than actions and logic.
Building blocks of OOP: The building blocks of OOP are
  • Class
  • Object
  • Every java program must start with a class, because using class only we can represent real world objects like person, Bike, Animal.

A MobileNumber is a VIP number if it satisfy the following conditions.


  1. The operator should be Vodafone.
  2. Atleast one 0 (Zero) should be exist in mobile number.
  3. The number should not end with 8.
  4. The single digit sum of all the digits in the number should be equal to 9. For example if the number is 9876543210, the sum is 9+8+7+...+1+0 = 45. Sum of 4+5 = 9.
Write a method: 
private boolean isVIPMobileNumber(String mobileNum, String operator)
mobileNum     phone number
operator

  
mobile operator as bsnl, Vodafone

import java.io.*;
import java.lang.*;
class Phno
{
String mobileNum;
String operator;
int count=0;
long sum=0;
long total_value=0;
 long value;
 long rem;
 long rem1;

private boolean isVIPMobileNumber(String mobileNum, String operator)
{
   this.mobileNum=mobileNum;
   this.operator=operator; 
  

   int len=mobileNum.length();
if(operator!="vadafone")
{
System.out.println("network is not vadafone");
    }

//System.out.println(len);
for(int i=0;i
{
   if(mobileNum.charAt(i)=='0')
{
count=count+1;
}
}
if(count>0)
{
}
else
{
System.out.println("at least one zero not avaliablee");
}

if(mobileNum.charAt(len-1)=='8'){
System.out.println("mobile number should not end with 8");
  }
value=Long.parseLong(mobileNum);

while(value!=0)
{
rem=value%10;
value=value/10;
sum=sum+rem;
}
//System.out.println(sum);
while(sum!=0)
{
    rem1=sum%10;
sum=sum/10;
total_value=total_value+rem1;
        }
if(total_value!=9)
{
System.out.println("sum of individual no's not equal to 9");
}
//System.out.println(total_value);
  
 System.out.println("VIP number");
 
return true;


}

public static void main(String[] args) 
{
String mno="9885603834";
String network="vadafone";
Phno pn=new Phno();
pn.isVIPMobileNumber(mno,network);

}
}

Monday 21 January 2013

Creating Alert dialogue boxes in Android:

public class ButtoneventActivity extends Activity implements View.OnClickListener {
    /** Called when the activity is first created. */
                private Button b1;
                private Button b2;
                private Button b3;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        b1=(Button)findViewById(R.id.button1);
        b1.setText("Click");
        b1.setOnClickListener(this);
        b2=(Button)findViewById(R.id.button2);
        b2.setText("alert");
        b2.setOnClickListener(this);
        b3=(Button)findViewById(R.id.button3);
        b3.setText("Conform");
        b3.setOnClickListener(this);
    }
                @Override
                public void onClick(View view) {
                                // TODO Auto-generated method stub
                                if(view==b1){
                                                AlertDialog showAlert=new AlertDialog.Builder(this).create();
                                                 showAlert.setTitle("it's clicked");
                                                 showAlert.setMessage("are you sure you want to Burn?");
                                                 showAlert.setButton("Burn",new OnClickListener(){
                                                                @Override
                                              public void onClick(DialogInterface dialog, int which) {
                                                                   // TODO Auto-generated method stub
                                                                                dialog.cancel();
                                                                }                                                             
                                                  });
                                                 showAlert.show();                         
                                        }
                                else if(view==b2){
                                               AlertDialog showAlert=new AlertDialog.Builder(this).create();
                                                 showAlert.setTitle("Button clicked");
                                                 showAlert.setMessage("are you sure you want to save?");
                                                 showAlert.setButton("save",new OnClickListener() {
                                                                @Override
                                                 public void onClick(DialogInterface dialog, int which) {
                                                                    // TODO Auto-generated method stub
                                                                                 dialog.cancel();
                                                                }       
                                       });
                                                 showAlert.setButton2("Cancle",new OnClickListener(){
                                                                                @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                                  //TODO Auto-generated method stub
                                                                                                 dialog.cancel();
                                                                                                                                                                                                       
                                       }                                 
                             });
                                                 showAlert.show();
                                }
                                else if(view==b3){
                                                AlertDialog showAlert=new AlertDialog.Builder(this).create();
                                                 showAlert.setTitle("Button clicked");
                                                 showAlert.setMessage("are you sure you want to save?");
                                                 showAlert.setButton("Yes",new OnClickListener(){
                                                                @Override
                                                  public void onClick(DialogInterface dialog, int which) {
                                                                        // TODO Auto-generated method stub
                                                                                 dialog.cancel();
                                                                }               
                               });
                                                 showAlert.setButton2("NO",new OnClickListener(){
                                                                                @Override
                                                      public void onClick(DialogInterface dialog, int which) {
                                                                               // TODO Auto-generated method stub
                                                                                                 dialog.cancel();               
                                                                                }     
                                                           });
                                                 showAlert.setButton3("Cancle",new OnClickListener(){
                                                                                @Override
                                     public void onClick(DialogInterface dialog, int which) {
                                                                // TODO Auto-generated method stub
                                                                                                 dialog.cancel();
                                                                                }      
                                        });  
                                  showAlert.show();   
                                               }
                             }
    }