String class methods

String class methods

List of methods which present in String class.

1. char charAt(int index)
return character from the specified index position.
2. int compareTo(Object o)
Compare string with another object.
3. int compareTo(String anotherString)
Compare two strings and return integer output
1 means first string is greater than second string,  -1 means first string is less than second string, 0 means both strings are equal.
4. int compareToIgnoreCase(String str)
compare two string with case insensitive.
5. String concat(String str)
concat two strings.
6. boolean contentEquals(StringBuffer sb)
return true if and only if the sequence of string is same as the specified string buffer.
7. boolean endsWith(String suffix)
return true if string ends with specified suffix.
8. boolean equals(Object anObject)
Compare the string with specified object.
9. boolean equalsIgnoreCase(String anotherString)
Compare the string with another string with case insensitive.
10. byte getBytes()
Encode the string in sequence of byte.
11. int hashCode()
return the hash code for the string.
12. int indexOf(int ch)
return index position of first occurrence of specified character.
13. int indexOf(int ch, int fromIndex)
return index position of first occurrence of specified character start from specified index.
14. int indexOf(String str)
return index of first occurrence of specified string.
15. int lastIndexOf(int ch)
return index of last occurrence of specified characters.
16. int length()
return the length of string.
17. boolean matches(String regex)
return true when string matches with given regular expression.
18. String replace(char oldChar, char newChar)
replacing all all character with new character in a string.
19. String replaceAll(String regex, String replacement)
replace each substring of string which matches with given regular expression from new string.
20. String[] split(String regex)
split string around matches of given regular expression.
21. String trim()
return string omitted leading and trailing white spaces.
22. String toUpperCase() 
Convert all the characters of a string in upper case.
23. String toString()
Conversion of object in to string.
24. String substring(int beginIndex)
return substring from the string start from specified index.
25. String substring(int beginIndex, int endIndex)
return substring from the string from specified start and end index.


What is the Difference between Method overloading and Overriding ?

What is the Difference between Method overloading and Overriding ?

Method Overloading :

Method overloading is the example of compile time polymorphism.

Some of the limitation in Java when we are declare the method within the class. We can't declare two methods in a class which have same name and signature and parameters.

So that we can overload such method by following process :

We can use same method name for both the methods but we are required to pass the parameters different to those methods.

It depends on type of argument, No. of argument, Sequence of argument.


Method Overriding :

Method overriding is performed in such case when we have two different classes and they are linked each other through Inheritance.

Both the classes contains method which have same name, signature and Argument.
What is the difference between Error and Exception in Java ?

What is the difference between Error and Exception in Java ?

Error :

It is Generated at compile time and reported by program at compile time only. They are like as missing some of the symbols which are required as per java programming.

Some of the statement which are showing declaration error, missing semicolon (;) error etc.


Exception : 

If the error which is generated at the time of run time which is called Exception. Exception are not the programming error. They generated due to input provided at run time and depends on the inputs only.

If sometime we can see the FileNotFoundException which is generated at run time because compile time doesn't check the content which we provided to program.
Getting started with PrimeFaces.

Getting started with PrimeFaces.

PrimeFaces is a lightweight library with one jar, zero-configuration and no required dependencies. You just need to download PrimeFaces, add the primefaces-{version}.jar to your classpath and import the namespace to get started.


  1. <html xmlns="http://www.w3.org/1999/xhtml"  
  2.     xmlns:h="http://java.sun.com/jsf/html"  
  3.     xmlns:f="http://java.sun.com/jsf/core"  
  4.     xmlns:p="http://primefaces.org/ui">  
  5.   
  6.     <h:head>  
  7.   
  8.     </h:head>  
  9.       
  10.     <h:body>  
  11.       
  12.         <p:spinner />  
  13.           
  14.     </h:body>  
  15. </html>  
What is JSF ?

What is JSF ?

JavaServer Faces (JSF) is a Java-based web application framework intended to simplify development integration of web-based user interfaces. JavaServer Faces is a standardized display technology which was formalized in a specification through the JavaCommunity Process.
How to apply rating bar in android

How to apply rating bar in android

Step 1 :

Put below code in your layout file :

<RatingBar    android:id="@+id/ratingBar"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_gravity="center"    android:numStars="5"    android:progressTint="@android:color/holo_orange_light"    android:layout_marginTop="10dp"    android:stepSize="1.0"    android:rating="0" />


here define the components which we are used :

ratingBar - id of RatinBar Component.

numStars - how many starts which you show for rating

progressTint  - Color of starts when we select for rating.

stepSize - when we click one time how may count we measure.

rating  - initial rating which we show on rating bar.


When we are using this RatingBar in Activity class so following methods are useful.

setRating - for any rating.

getRating  - get the current rating from the RatingBar.
Android back button event with example

Android back button event with example

Android device back button is to navigate from current activity to previous activity. In that case we are using below code for handing event on back button.

Declare variable in class :

1. boolean doubleBackToExitPressedOnce = false;

2. put code after onCreate method on an activity.

@Override
 public void onBackPressed() {
        if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

        this.doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                doubleBackToExitPressedOnce = false;
            }
        }, 2000);
    }

Regex Character Classes with example

Regex Character Classes with example

Regex Character Classes :

[abc] : a,b or c characters only

[^abc] : Any character except a, b or c character.

[a-zA-Z] : a through z or A through Z, inclusive range.

[a-d[m-p]] : a through d or m through p

[a-z&&[def]] : d, e or f intersection.

[a-z&&[^bc]] : a through z except b and c

[a-z&&[^m-p]] : a through z and not m through p


4. Regex qualifiers :

X? : X occurs once or not at all.

X+ : X occurs once or more times.

X* : X occurs 0 or more times.

X{n} : X occurs n times only.

X{n,} : X occurs n or more times.

X{y,z} : X occurs at least y times but leass than z times.

import java.util.regex.*;

class RegexExample4{
public static void main(String args[]){

System.out.println("? quantifier ....");
System.out.println(Pattern.matches("[amn]?", "a"));//true (a or m or n comes one time)
System.out.println(Pattern.matches("[amn]?", "aaa"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aammmnn"));//false (a m and n comes more than one time)
System.out.println(Pattern.matches("[amn]?", "aazzta"));//false (a comes more than one time)
System.out.println(Pattern.matches("[amn]?", "am"));//false (a or m or n must come one time)

System.out.println("+ quantifier ....");
System.out.println(Pattern.matches("[amn]+", "a"));//true (a or m or n once or more times)
System.out.println(Pattern.matches("[amn]+", "aaa"));//true (a comes more than one time)
System.out.println(Pattern.matches("[amn]+", "aammmnn"));//true (a or m or n comes more than once)
System.out.println(Pattern.matches("[amn]+", "aazzta"));//false (z and t are not matching pattern)

System.out.println("* quantifier ....");
System.out.println(Pattern.matches("[amn]*", "ammmna"));//true (a or m or n may come zero or more times)

}
What is regex in Java and How to use it.

What is regex in Java and How to use it.

Java Regex :

Java Regex and regular expression is an API which define pattern for searching or manipulating strings.

It provides following classes and interface for regular expression.

(i)   MatcherResult Interface
(ii)  Matcher class
(iii) Pattern class
(iv)  PatternSyntaxExeption class

Matcher class implements MatcherResult Interface which contains following methods.

(i) boolean matches() : test whether the regular expression matched the pattern.

(ii) boolean find() : find the next expression that matches the pattern.

(iii) boolean find(int start) : find the next expression that matches the pattern from the given start number.

Pattern Class : it is compiled version of a regular expression.

(i) static Pattern compile(String regex) : compile the given regex and return instance of Pattern class.

(ii) Matcher matcher(CharSequence input) : creates the matcher that matches the given input.

(iii) String Pattern() : return the regex pattern.

(iv) static boolean matches(String regex, CharSequence input) : it works as the combination of the compile and matcher methods.

Ex :

import java.util.regex.*;

public class RegexExample{

public static void main(String ar[]){

Pattern p = Pattern.compile(".s");
Matcher m = p.matcher("as");

boolean b1 = m.matches();

// OR

boolean b2 = Pattern.compile(".s").matcher("as").matches();

// OR

boolean b3 = Pattern.matches(".s","as");


}
What is Java Bean with Example

What is Java Bean with Example

Java Bean : Java bean is a class which contains all the properties are private and contains getter/setter methods corresponding to that.

A public non-argument constructor is present in it.

It implements Serializable interface which have no methods defined in it.

Bean is basically used for serialization of data and maintain its state during transfer.

public class Employee implements Serializable{

   private int id;
   private String name;  
   private int salary;

   public Employee() {}

   public Employee(String name, int salary) {
      this.name = name;
      this.salary = salary;
   }
   public int getId() {
      return id;
   }
   public void setId( int id ) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName( String name ) {
      this.name = name;
   }
   public int getSalary() {
      return salary;
   }
   public void setSalary( int salary ) {
      this.salary = salary;
   }
}
How to check internet is connected  or not in android

How to check internet is connected or not in android

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;


public class NetworkCheck {

    public static boolean hasInternetConnection(Context context)
    {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected())
        {
            return true;
        }
        NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected())
        {
            return true;
        }
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected())
        {
            return true;
        }
        return false;
    }
}

put below permissions in manifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Replace html contents using jQuery

Replace html contents using jQuery

$('li').html('New HTML');  // this replaced all list items on your page with specified contents.

$('div').html('New Div Contents');  // this replaced all div contents on your page with specified contents.

$('body').html('New Body Contents'); // this replaced all contents of body part of your page.

$('p').html('New Paragraph contents'); // this replaced all paragraphs on your page with specified contents. 
What is $(document).ready() ?

What is $(document).ready() ?

What is $(document).ready() ?

Before you can safely use jQuery to do anything to your page, you need to ensure that the page is in a state where its can be manipulated.

like as :

$(document).ready(function(){

alert("Page is ready for manipulation.");
});


$(document) is used for creating object of our page document.

ready() is used for indication for page is in ready state.
What is thread in Java.

What is thread in Java.

Thread is a program in execution. All Java programs have at least one thread, known as the main thread, which is created by the JVM at the program’s start, when the main() method is invoked with the main thread. In Java, creating a thread is accomplished by implementing an interface and extending a class. Every Java thread is created and controlled by the java.lang.Thread class.

When a thread is created, it is assigned a priority. The thread with higher priority is executed first, followed by lower-priority threads. The JVM stops executing threads under either of the following conditions:
  • If the exit method has been invoked and authorized by the security manager

  • All the daemon threads of the program have died
Explanation of oops concepts

Explanation of oops concepts

Object means a real word entity such as pen, chair, table etc.Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts:
  • Object
  • Class
  • Inheritance
  • Polymorphism
  • Abstraction
  • Encapsulation

Object

Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
How to load pdf file in your android application

How to load pdf file in your android application

WebView webview = (WebView) findViewById(R.id.webview);

webview.getSettings().setJavaScriptEnabled(true);

webview.getSettings().setBuiltInZoomControls(true);
webview.loadUrl("https://docs.google.com/gview?embedded=true&url=<PDF_COMPLETE_URL>");

webview.setWebViewClient(new WebViewClient() {
           @Override
           public void onPageFinished(WebView view, String url) {
                            
            }
});
Webview in android

Webview in android

WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application.

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/webview"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
/>
WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("http://www.google.com");

If you click on any link inside the webpage of the webview, that page will not be loaded inside your webview so in that case we need to extend our class from WebViewClient and override its method.

private class MyBrowser extends WebViewClient {
   @Override
   public boolean shouldOverrideUrlLoading(WebView view, String url) {
      view.loadUrl(url);
      return true;
   }
}
What is intent?

What is intent?

It is a kind of message or information that is passed to the components. It is used to launch an activity, display a web page, send sms, send email etc. There are two types of intents in android:
  1. Implicit Intent : It is used to invoke the system components.
  2. Explicit Intent : It is used to invoke the activity class.
Java 7 Features

Java 7 Features

1. Strings in Switch:

public void testStringInSwitch(String param){
       final String JAVA5 = "Java 5";
       final String JAVA6 = "Java 6";
       final String JAVA7 = "Java 7";
       switch (param) {
           case JAVA5:
               System.out.println(JAVA5);
               break;
           case JAVA6:
               System.out.println(JAVA6);
               break;
           case JAVA7:
               System.out.println(JAVA7);
               break;
       }
   }
 
2. Binary Literals:

public void testBinaryIntegralLiterals(){
        int binary = 0b1000; //2^3 = 8
        if (binary == 8){
            System.out.println(true);
        } else{
            System.out.println(false);
        }
}

3. Underscore Between Literals:

public void testUnderscoresNumericLiterals() {
    int oneMillion_ = 1_000_000; //new
    int oneMillion = 1000000;
    if (oneMillion_ == oneMillion){
        System.out.println(true);
    } else{
        System.out.println(false);
    }
}

4. Diamond Syntax:

public void testDinamond(){
    List list = new ArrayList<>();
    Map> map = new HashMap<>();
}


5. Multi-Catch Similar Exceptions:

public void testMultiCatch(){
    try {
        throw new FileNotFoundException("FileNotFoundException");
    } catch (FileNotFoundException | IOException fnfo) {
        fnfo.printStackTrace();
    }
}


6. Try with Resources:

public void testTryWithResourcesStatement() throws FileNotFoundException, IOException{
    try (FileInputStream in = new FileInputStream("java7.txt")) {
        System.out.println(in.read());
    }
}  

Difference between path band classpath in Java

Difference between path band classpath in Java

1).Path is an environment variable which is used by the operating system to find the executables.

Classpath is an environment variable which is used by the Java compiler to find the path, of classes.ie in J2EE we give the path of jar files.


2).PATH is nothing but setting up an environment for operating system. Operating System will look in this PATH for executables.

Classpath is nothing but setting up the environment for Java. Java will use to find compiled classes

3).Path refers to the system while classpath refers to the Developing Envornment.

In path we set the path of executables while in
classpath we set path of jars for compiling classes.
Random String Generation in Java

Random String Generation in Java

import java.util.Random;

public class RandomStringGen {


private static final String CHAR_LIST =
       "1234567890";
   private static final int RANDOM_STRING_LENGTH = 4;
   
   /**
    * This method generates random string
    * @return
    */
   public String generateRandomString(){
       
       StringBuffer randStr = new StringBuffer();
       for(int i=0; i<RANDOM_STRING_LENGTH; i++){
           int number = getRandomNumber();
           char ch = CHAR_LIST.charAt(number);
           randStr.append(ch);
       }
       return randStr.toString();
   }
   
   /**
    * This method generates random numbers
    * @return int
    */
   private int getRandomNumber() {
       int randomInt = 0;
       Random randomGenerator = new Random();
       randomInt = randomGenerator.nextInt(CHAR_LIST.length());
       if (randomInt - 1 == -1) {
           return randomInt;
       } else {
           return randomInt - 1;
       }
   }
   

}

Run task periodically in Java

Run task periodically in Java

Schedular Task :

For this functionality,

You should create a class extending TimerTask(available in java.util package). TimerTask is a abstract class.
Write your code in public void run() method that you want to execute periodically.
Insert below code in your Main class.

import java.util.TimerTask;
import java.util.Date;
/**
 * 
 * @author Dhinakaran P.
 */
// Create a class extends with TimerTask
public class ScheduledTask extends TimerTask {

Date now; // to display current time

// Add your task here
public void run() {
now = new Date(); // initialize date
System.out.println("Time is :" + now); // Display current time
}
}

Run Scheduler Task :

A class to run above scheduler task.

Instantiate Timer Object Timer time = new Timer();
Instantiate Scheduled Task class Object ScheduledTask st = new ScheduledTask();
Assign scheduled task through Timer.shedule() method.
import java.util.Timer;

/**
 * 
 * @author Dhinakaran P.
 */

//Main class
public class SchedulerMain {
public static void main(String args[]) throws InterruptedException {

Timer time = new Timer(); // Instantiate Timer Object
ScheduledTask st = new ScheduledTask(); // Instantiate SheduledTask class
time.schedule(st, 0, 1000); // Create Repetitively task for every 1 secs

//for demo only.
for (int i = 0; i <= 5; i++) {
System.out.println("Execution in Main Thread...." + i);
Thread.sleep(2000);
if (i == 5) {
System.out.println("Application Terminates");
System.exit(0);
}
}
}
}
Output:

Execution in Main Thread....0
Time is :Tue Jun 19 14:21:42 IST 2012
Time is :Tue Jun 19 14:21:43 IST 2012
Execution in Main Thread....1
Time is :Tue Jun 19 14:21:44 IST 2012
Time is :Tue Jun 19 14:21:45 IST 2012
Execution in Main Thread....2
Time is :Tue Jun 19 14:21:46 IST 2012
Time is :Tue Jun 19 14:21:47 IST 2012
Execution in Main Thread....3
Time is :Tue Jun 19 14:21:48 IST 2012
Time is :Tue Jun 19 14:21:49 IST 2012
Execution in Main Thread....4
Time is :Tue Jun 19 14:21:50 IST 2012
Time is :Tue Jun 19 14:21:51 IST 2012
Application Terminates
Time is :Tue Jun 19 14:21:52 IST 2012