Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts
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.


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;
   }
}
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.
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;
       }
   }
   

}