Requirement is to search a particular String in the Array of String value. To achieve this we need to have some set string values in a String array and secondly we need to have a String value to be searched.

Tips to Proceed...

1. Take counter
2. Iterate String and match the value on each iteration using equals() method.

Steps to do....

1. Take a counter count=0 .
2. Get the String to be searched.
3. Iterate the String Array and keep on searching from index=0 till length.
4. While looping keep on matching the string value with each index value of the Array.
5. If it get matched print "Match Found" and increment a counter.
6. If not matched then Print " No Match Found ".

Program :


public class Lab1{

    public static void main(String args[]){

 int count=0;
  
 String arr[]= new String[10];
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter the String ");

 for(int i=0;i<10;i++){    // Iterate loop to store value in Array
     System.out.print((i+1)+". ");
     arr[i]=sc.next();
 }

 System.out.println("Enter the String to be searched");
 String s=sc.next();      // Enter value to be searched
  
 for(int i=0;i<arr.length;i++){ // Loop to search the Element
     if(s.equals(arr[i])){  
  System.out.println("Match Found");
  count++;
     }
 }
        
        if(count==0)     // Checking No Such Element Present in Array
          System.out.println("No Element Found ");

 System.out.println("No of Words Found in Number:"+count);
  
 }
}










The above question means that we need to execute some line of code which perform something before the main() method execution. As we know that when we execute our program JVM will call main() at very first , so it seems that its not possible to perform something before the main() method execution but is possible with the static initialization block and calling method while initializing static variable 

Important Points :

1. Static initialized will always be executed before main() method calling by JVM.
2. Final static variable can be initialized using static initialization block.

1st Approach by static initialization block: 

Program :

public class Lab1 {

    static {                       // static initialization block
 int sum=10+20;
 System.out.println("SUM:"+sum);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}

In the above program sum=10+20 will be executed before main() method and hence output will look like ,
SUM:30
main() method

NOTE : We can also call a static method from static initialization block which too can perform some task which will always counted before main() method execution.


public class Lab1 {

    static {                 // static initialization block
 int s=Lab1.sum(10,20);
        System.out.println("SUM:"+s);
    }

    public static int sum(int a,int b ){
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}


Now in the above program static sum() method will be called first before main() method. And the output will look like ,

SUM:30
main() method

2nd Approach by Calling static method while initializing static variable :

public class Lab1 {

    static int x=Lab1.sum(10,20); 

    public static int sum(int a,int b ){
        System.out.println("SUM:"+(a+b));
        return (a+b);
    }

    public static void main(String[] args) { // main method
 
       System.out.println("main() method");
    }

}



In the above program at the time of call loading JVM will try to initialize the static variable 'x' here and while initializing it will call static method sum(). So this method will be executed before the main() method execution. The output will look like,

SUM:30
main() method








This question might be asked in as interview to judge logic on how you are going to achieve without providing you the length() method to calculate the String length easily.

Tips to Think ....

1. As we know that in Java String doesn't end with the NULL character with in C it ends with the NULL character.
2. To get to the end of String we have nothing as a mark in Java but in C we can check for the NULL character.
3. Now have to think to get the mark to the end of the String.
4. One way of doing is to caught the Exception if JVM will throw "StringIndexOutOfBoundsException" if we try to access the extra index of the String.

Steps to do :

1.Initialize a count i.e c=0;
2. Run the while loop making it true ( goes infinite looping ).
3. Within the loop access the String using charAt() at each index.
4. After accessing it last index if it try to access the next index which is not actually present in the memory will will raise to "StringIndexOutOfBoundsException" and we need to caught the exception within try-catch block.
5. Keep Increasing the counter after each iteration.
6. Print the Counter at the catch block will give the length of the String.
7. Use the break statement to break the infinite looping with the while(true).

Program

public class Lab1 {

    public static void main(String[] args) {
  
        String s1="sushant";
 int count=0;
 int i=0;
 while(true){
        try{
    s1.charAt(i);
           i++;
    count++;
        }catch(StringIndexOutOfBoundsException e){
    System.out.println("String Length is : "+count);
    break;
       }
  }
     }
}





This is a interview question can be asked in an experienced or fresher's interview to write a program which will add up all the integer value present in a string and print the added number.

Tips to think how to do it...

1. For this kind of problem always think of first matching the number in a String .
2. How you are going to match?
3. The only simplest way is with the help of ASCII of 0-9 .

Steps to do :

1. Take a int variable c=0.
2. Run the loop from 0 to String length.
3. Get the each index value using charAt() method which will return the char value.
4. Convert that char into int by typecasting or any other way.
5. Now check that ASCII fall into the range of 48-57 for 0-9 int number.
6. If it matches then first convert that number into integer using Integer.parseInt().
7. Then add with the c and store to the same variable i.e c.
8. Repeat from 3-7 till the end of the loop.
9. At the end of loop , Print c outside the loop.

Program


public class Lab1 {

   public static void main(String[] args) {
 
 String s="s16u7ty9";
 int c=0;
 for(int i=0;i<s.length();i++){
    char ch=s.charAt(i);         // Getting each char from String
    int x=(int)ch;               
    for(int y=48;y<=57;y++){       // Loop for checking the ASCII
       if(x==y){
   int num=Integer.parseInt(""+ch); //Getting the int value
   c=c+num;
       }
    }
 }
 System.out.println("Total Sum:"+c); // Final sum 

   }

}







This is one of the important and mostly asked question in fresher and experienced interview. Singleton class means a class with only one object. It will have only one object which will be returned always when ever we try to create the object of singleton class. We can create our own singleton class. Interviewer will ask you to write your own singleton class, for that you need to remember following points to create your own singleton class :

a) Declare a static resource ( Object of the singleton class ) .
b) Create that resource in the static initialization block so that will be creating at the class loading time.
c) There must be a static method which return the resource.
d) Most importantly Constructor should be made private. 

Hello.java

class Hello{

   static Hello hello;
   
   private Hello(){}

   static {

     hello = new Hello(); 

   }

   public static Hello getHello(){

        return hello;
   
   }

}


A. java

class A{

  public static void main(String[] args){

     Hello h = Hello.getHello();  // return the object created at class loading.
     Hello h1 = Hello.getHello(); // It will also return the same object. 

  }
}




Hello class is the singleton class in which Hello is created in the static initialization block so that object will be created once which is at the time of class loading and will be returned as many times we try to create an object of Hello class. 

Why Constructor is made private ?

It is because object shouldn't be created directly using new operator.

Explanation :

As the Hello class ( Singleton class ) will be loaded the static initialization block will be executed and hence resource will be created and then whenever we call getHello() method it will always return the object created at the time of class loading. 

This is one of the common question to be asked in interview to judge your basic level of knowledge. We all know that String is immutable which means that once object created cannot be modified or if try to modify, it will create another String literal in the String pool. So this proves that String is immutable, but this is we are proving theoretically. Now if interviewer ask you to prove the same by writing programs then you will be doing like this,

class A{

  public static void main(String[] args){

     String s="java";  // Create a object in String pool.

     s = s + "java" ; // Create another object with "javajava" as 
                         String literal in the String pool

  }

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic