Core Java

Q :What are advantages/drawbacks of Maven

Ans:
  • Helps manage all the processes, such as building, documentation, releasing, and distribution in project management
  • Simplifies the process of project building
  • Increases the performance of the project and the building process
  • The task of downloading Jar files and other dependencies is done automatically
  • Provides easy access to all the required information 
  • Makes it easy for the developer to build a project in different environments without worrying about the dependencies, processes, etc.
  • In Maven, it’s easy to add new dependencies by writing the dependency code in the pom file
Conversely, Maven has a few drawbacks.
  • Maven requires installation in the working system and the Maven plug-in for the IDE
  • If the Maven code for an existing dependency is unavailable, you cannot add that dependency using Maven itself
  • Some sources claim that Maven is slow

Q: What Java System.out.println() is used to ?

Ans:
System: It is a final class defined in the java.lang package.
out: This is an instance of PrintStream type, which is a public and static member field of the System class.
println(): As all instances of PrintStream class have a public method println(), hence we can invoke the same on out as well. This is an upgraded version of print().
It prints any argument passed to it and adds a new line to the output. We can assume that System.out represents the Standard Output Stream.

Q: How to put condition on keys in map in java ?

Ans:
HashMap<Integer,String> map = new HashMap<Integer, String>();
map.put(1,"Dheeraj");
map.put(2,"Arul");

for(Integer s: map.keySet())
{
if(s%2==0)
System.out.println(map.get(s));
}

Q: What is public static void main(String[] args) in java

Ans:
The Java compiler or JVM looks for the main method when it starts executing a Java program. The signature of the main method needs to be in a specific way for the JVM to 
recognize that method as its entry point. If we change the signature of the method, the program compiles but does not execute.
The execution of the Java program, the java.exe is called. The Java.exe in turn makes Java Native Interface or JNI calls, and they load the JVM. The java.exe parses 
the command line, generates a new String array, and invokes the main() method. A daemon thread is attached to the main method, and this thread gets destroyed only when the Java program 
stops execution.

Java main() Method

Q : How to remove duplicate Values from the map using java

Ans :

//Creating a map which contains duplicate values
            HashMap<String, String> map = new HashMap<String, String>();
            map.put("A", "1");
            map.put("B", "2");
            map.put("C", "2");
            map.put("D", "3");
            map.put("E", "3");

//Creating a map which is empty
            HashMap<String, String> mapNew = new HashMap<String, String>();
  
//Adding only unique records in New map
          
                for(String s :map.keySet())
                {
                    
                    System.out.println(s +"=="+map.get(s));
                    
                    if(!mapNew.containsValue(map.get(s)))
                    {
                        mapNew.put(s, map.get(s));
                    }
                 }

//printing New map               
             System.out.println(mapNew);


Q:What is the Output Of the following Program

(1).
    public static void main(String args[])
    {
        String str = "Java Programming";
        String str1 = "Java Programming";
  
        String str2 = str1;
        if (str.equals(str1))
            System.out.println("Equal Case 1");
        if (str == str1)
            System.out.println("Equal Case 2");
    }
Output:
Equal Case 1
Equal Case 2

Explanation:
The equals() method compares the characters inside a String object.Thus str.equals(str1) comes out to be true.
The == operator compares two object references to see whether they refer to the same instance. Now str points to “Java Programming” and then str1 also points to “Java Programming”, 
hence str == str1 is also true.

(2).

    public static void main(String args[])
    {
        String str = "JavaProgramming";
        String str1 = "Java";
  
        System.out.println(str.compareTo(str1));
        System.out.println(str1.compareTo(str));
    }

Output:
11
-11

Explanation:
The String method compareTo( ) serves the purpose of comparing two strings. Whether one string is less than, greater than or equal to the second string.
In case 1, comparing JavaProgramming with Java implies JavaProgramming is greater than Java by 11 characters.
In case 2, comparing Java with JavaProgramming implies Java is lesser than JavaProgramming by 11 characters (-11).

(3).

String text = "Hello, world!";

String replacedText = text.replace('o', 'X');
// Result: HellX, wXrld!
String replacedTextRegex = text.replaceAll("[aeiou]", "X");
// Result: HXllX, wXrld!

Explanation:
The replace(char oldChar, char newChar) method replaces all occurrences of one character in the invoking string with another character.
Hence ‘a’ replaced with a ‘9’.
replaceAll(String regex, String replacement) is more flexible and supports pattern-based matching and replacement using regular expressions.


Q: State the difference between the new operator and without a new operator in a string.

Ans: 
String string=” Software Testingo”
Whenever we create an object of String object with a double quote, it allocates the memory in the string literal pool in the indexing manner.
String string=new String(“Software Testingo”);
Whenever we create the String object with the new operator, it allocates memory for the String object in the heap area in the indexing manner.

Q: What is Logical operators in JsonPath ?

Ans:
Just like any programming language, JsonPath supports all the logical operators. Below is the list of Logical Operators that we can use to create expressions. Every logical operator is discussed in detail below.

Operator Description
==         left is equal to right (note that 1 is not equal to '1').
!=         left is not equal to right.
<         left is less than right.
<=         left is less or equal to right.
>         left is greater than right.
>=         left is greater than or equal to right.

Ex :
Equals to (==) operator in JsonPath
As the name suggests the operator checks if the left-hand side is equal to the right-hand side. Let us find out all the books that have 352 pages. Here is the JsonPath

JsonPath:  $.books[?(@.pages == 352)]    

Q:How to Get information from the properties file ?

Ans:
public class Test {  
public static void main(String[] args)throws Exception
{  
    FileReader reader=new FileReader("path of properties file");        
    Properties p=new Properties();  
    p.load(reader);        
    System.out.println(p.getProperty("user"));  
    System.out.println(p.getProperty("password"));  
}  

Q: How to read json File?

Ans:
                JSONParser parser = new JSONParser();
      try {
         Object obj = parser.parse(new FileReader("sample.json"));
         JSONObject jsonObject = (JSONObject)obj;
         String name = (String)jsonObject.get("firstName");
         String course = (String)jsonObject.get("lastName");
         JSONArray subjects = (JSONArray)jsonObject.get("phoneNumbers");
         System.out.println("Name: " + name);
         System.out.println("Course: " + course);
         System.out.println("Subjects:");
         Iterator iterator = subjects.iterator();

         while (iterator.hasNext()) {
            System.out.println(iterator.next());
         }

Q: What do you mean by public ,protected and private in java

Ans:
If the class member declared as public then it can be accessed everywhere.
If the class members declared as protected then it can be accessed only within the class itself and by inheriting child classes.
This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface.
If the class members declared as private then it may only be accessed by the class that defines the member.
This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes.
Package(Default) Access Modifier  
A class or method or variable declare without any access modifier then is considered that it has a package(default)access modifier The default modifier act as public within the same package and acts as private outside the package. If a class is declared as default then we can access that class only within the current package i.e from the outside package we can’t access it. Hence, the default access modifier is also known as the package–level access modifier. A similar rule also applies for variables and methods in java.


Q: WAP to count the character in a String

Ans:
@Test
public void charCount3()
{
String str = "crackAutomationinterview";  
//HashMap char as a key and occurrence as a value  
HashMap <Character, Integer> charCount = new HashMap<>();  
for (int i = 0; i<=str.length()-1; i++)   
{  
if(charCount.containsKey(str.charAt(i)))   //check key of each string char
{  
int count = charCount.get(str.charAt(i));  //check value of key
charCount.put(str.charAt(i), count+1);  //put key and value with 1 increment
}   
else   
{  
charCount.put(str.charAt(i),1);  //if not found then put value as 1
}  
}  
System.out.println(charCount);  
}  

Q: WAP to find the duplicate character in a String

Ans:
@Test
public void duplicateChar()
{
String str = "crackAutomationinterview";  
char[] c = str.toCharArray();
                label:
for (int i = 0; i<c.length; i++)   
{  
for (int j = i+1; j <c.length; j++)
    {
if(c[i]==c[j])
System.out.println(c[i]+" : is duplicate");
                                break label;                                        //it is labeled break which will come out nested loop
    }
 
        }  
}


Q: WAP to check number is palindrome or not?

Ans:
@Test
public void palindromeInt()
{
int old=1234321;
String olds=String.valueOf(old);
StringBuffer s =new StringBuffer(olds);
String news = s.reverse().toString();
System.out.println(olds +"---->"+news);
if(olds.equals(news))
{
   System.out.println("yes");
}
else
System.out.println("No");

}
@Test
public void palindromeInt2()
{
int n=12321;
int r,sum=0,temp;
temp=n;
while(n>0)
{
r=n%10; //give u last number
sum=sum*10+r; //put at first place
n=n/10; //gives u second last int
}
if(temp==sum)
{
   System.out.println("yes");
}
else
System.out.println("No");

}

Q: WAP to sort any integer array

Ans:
@Test
public void sortingArray()
{
int[] c = {1,0,2,0,3,4,5};
int temp=0;
for (int i = 0; i<c.length; i++)   
for (int j = i+1; j<c.length; j++)   
if(c[i]<c[j]) // for desc  <=====> if(c[i]>c[j])  for Asc
{
temp=c[i];
c[i]=c[j];
c[j]=temp;
}
}
}
System.out.println("===sorted array :====");
for (int i = 0; i<c.length; i++)   
System.out.print(" "+c[i]);
}
}


Q: WAP to check max/min in any inter array

Ans:
@Test
public void max() {
System.out.println("===================max in array=================");
int[] c = {9,2,13,4,8};
int max =c[0];
for(int i=0;i<c.length;i++)
{
if(c[i]>max)
max =c[i];
}
System.out.println("max is :"+max);
}

Q: WAP to remove duplicate from the list

Ans:

      public void printUniqueList2() 
    {
      System.out.println("===================remove duplicate from array list=================");
      List<Integer> myList = Arrays.asList(10,15,8,49,25,98,98,32,15);
      ArrayList<Integer> newList = new ArrayList<Integer>();
      
      for(Integer i: myList)
      {
      if(!newList.contains(i))
      newList.add(i);
      }
        System.out.println("unique list is = "+newList);  
}

Q:WAP to check if two strings are anagrams

Ans:
@Test
public void anagrams()
{
System.out.println("===================two strings are anagrams=================");
String s1= "quescol"; 
String s2= "colsque";
char[] arr1=s1.toCharArray();
char[] arr2=s2.toCharArray();

Arrays.sort(arr1);
Arrays.sort(arr2);

if(Arrays.equals(arr1,arr2))
System.out.println("yes");
else
System.out.println("No");
}
@Test(priority=5)
public void startwith() {
System.out.println("======find out all the numbers starting with 1 using Stream functions==========");
List<Integer> myList = Arrays.asList(10,15,8,49,25,98,32);
                 myList.stream().map(s -> s + "").filter(s -> s.startsWith("1")).forEach(System.out::println);
}

Q: How to generate random number in Java

Ans:
Random random = new Random();   
// Generates random integers 0 to 49  
int x = random.nextInt(50);   
// Generates random integers 0 to 999  
int y = random.nextInt(1000);   
// Prints random integer values  
System.out.println("Randomly Generated Integers Values");  
System.out.println(x);   
System.out.println(y); 

Q:Can we keep other statements in between try catch and finally blocks

Ans:
No, we cannot write any statements in between try, catch and finally blocks and these blocks form one unit.

Q: How to connect with oracle database in java

Ans:

try
{  
//step1 load the driver class  
Class.forName("oracle.jdbc.driver.OracleDriver");  
  
//step2 create  the connection object  
Connection con=DriverManager.getConnection(  
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  
//step3 create the statement object  
Statement stmt=con.createStatement();  
  
//step4 execute query  
ResultSet rs=stmt.executeQuery("select * from emp");  
while(rs.next())  
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));  
  
//step5 close the connection object  
con.close();  
}

catch(Exception e)
System.out.println(e);
}  

Q: Can we change the order of public static void main in java

Ans:
Yes, we can change the order of public static void main() to static public void main() in Java, the compiler doesn't throw any compile-time or runtime error. In Java, we can declare access modifiers in any order, the method name comes last, the return type comes second to last and then after it's our choice.
  

Q: Difference between StringBuffer and StringBuilder

Ans:


Q: How to convert date into String ?

Ans:
public static void main(String[] args) 
{  
    Date date = new Date();  
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");  
    String strDate = formatter.format(date);  
    System.out.println("Date Format with MM/dd/yyyy : "+strDate);  
  
    formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");  
    strDate = formatter.format(date);  
    System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);  
  
    formatter = new SimpleDateFormat("dd MMMM yyyy");  
    strDate = formatter.format(date);  
    System.out.println("Date Format with dd MMMM yyyy : "+strDate);  
  
    formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");  
    strDate = formatter.format(date);  
    System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);  
  
    formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");  
    strDate = formatter.format(date);  
    System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);  

Q:Can we execute main method without static?

Ans: You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program.

Q: How to use switch case in Java ?

Ans:
    switch(expression) {
      case x:
    // code block
    break;
      case y:
    // code block
    break;
      default:
    // code block
    }
Note :Java has not allowed boolean, double, and float in Switch Statement.

Q: What is the difference between HashMap and Hashtable?

Ans:
1) HashMap is not synchronized but Hashtable is synchronized.
2) HashMap can contain one null key and multiple null values. But Hashtable cannot contain any null key or null value.
3) HashMap is not thread-safe, so it is useful for non-threaded applications.But Hashtable is thread-safe, and it can be shared between various threads.
4) HashMap inherits the AbstractMap class But Hashtable inherits the Dictionary class.

Q:How to iterate into a json file containing Json Array ?

Ans:

{
  "name": "Royal Challengers Bangalore",
  "location": "Bangalore",
  "player": [
    {
      "name": "Faf Du Plessis",
      "country": "South Africa",
      "role": "Batsman",
      "price-in-crores": "7"
    },
    {
      "name": "Virat Kohli",
      "country": "India",
      "role": "Batsman",
      "price-in-crores": "15"
    },
    {
      "name": "Glenn Maxwell",
      "country": "Australia",
      "role": "Batsman",
      "price-in-crores": "11"
    },
    {
      "name": "Mohammad Siraj",
      "country": "India",
      "role": "Bowler",
      "price-in-crores": "7"
    },
    {
      "name": "Harshal Patel",
      "country": "India",
      "role": "Bowler",
      "price-in-crores": "10.75"
    },
    {
      "name": "Wanindu Hasaranga",
      "country": "Srilanka",
      "role": "Bowler",
      "price-in-crores": "10.75"
    },
    {
      "name": "Dinesh Karthik",
      "country": "India",
      "role": "Wicket-keeper",
      "price-in-crores": "5.5"
    },
    {
      "name": "Shahbaz Ahmed",
      "country": "India",
      "role": "All-Rounder",
      "price-in-crores": "2.4"
    },
    {
      "name": "Rajat Patidar",
      "country": "India",
      "role": "Batsman",
      "price-in-crores": "0.20"
    },
    {
      "name": "Josh Hazlewood",
      "country": "Australia",
      "role": "Bowler",
      "price-in-crores": "7.75"
    },
    {
      "name": "Mahipal Lomror",
      "country": "India",
      "role": "Bowler",
      "price-in-crores": "7.75"
    }
  ]
}


import net.minidev.json.JSONArray;
import net.minidev.json.JSONObject;
import net.minidev.json.parser.JSONParser;
import org.testng.annotations.Test;
import java.io.FileReader;
import java.util.Iterator;
public class ReadJson {

    @Test
    public void readjson() {
        int count=0;
        int foreigncount =0;

        try {
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(new FileReader("TestJson.json"));
            JSONObject jsonObject = (JSONObject) obj;
            JSONArray subjects = (JSONArray) jsonObject.get("player");
            int jsonarraysize = ((JSONArray) jsonObject.get("player")).size();

            for(int i=0;i<jsonarraysize;i++)
            {
                JSONObject records = (JSONObject)  subjects.get(i);
                if(records.get("role").toString().equals("Wicket-keeper"))
                    count=count+1;
                if(!records.get("country").toString().equals("India"))
                    foreigncount=foreigncount+1;
            }
         
            
            if(count==1)
                System.out.println("There is only one Wicket keeper in list");
            else
                System.out.println("There is more than one Wicket keeper in list");

            if(foreigncount==4)
                System.out.println("There is only 4 foreign players in list");
            else
                System.out.println("There is more than 4 foreign players in list");

        }
        catch (Exception e) {
            System.out.println("There is some error in list");
        }
    }
}

Q:How to print future date in java?

Ans:
SimpleDateFormat dateformat = new SimpleDateFormat("MM/dd/yyyy");
Date date =new Date();
Calender cal = Calender.getInstance();
cal.setTime(date);
cal.add(calender.DATE , 1)
Date currentdateplusOne = cal.getTime();
String futuredate =dateformat.format(currentdateplusOne);

Q:What is difference between Abstract class and interface ?

Ans:

  • Abstract class can have constructor but interface cant.
  • We cant create object for both

Q: WAP to get pair of element which gives sum of 7 in an  integer array

Ans:
public static void main(String[] args) {
        int intarray[] = {2,4,3,5,0,7,6,1};
        
        for (int i =0 ; i<intarray.length;i++)
        {
            
            for(int j=i+1; j<intarray.length;j++)
            {
                if(intarray[i] + intarray[j] == 7)
                System.out.print(intarray[i] +","+intarray[j]); //4 3, 0 7, 6 1
                System.out.println();
                
            }
        }
    }

Q: WAP to reverse half elements in integer array

Ans:
   int a[] = {1,2,3,4,5,6,7,8,9,10}; 
   //source array  
   for(int i=(a.length/2) , j=a.length-1 ; i<ji++ , j--)
      {
        int temp=a[i];
        a[i]=a[j];
        a[j]=temp;
      }

   System.out.println("The Output Is:");
   for(int i=0;i<a.length;i++)
     {
        System.out.print(" "+a[i]);      
     }

The Output Is:
 1 2 3 4 5 10 9 8 7 6

Q: WAP in java to find max and min number by passing array in function

Ans:
  public class array 
  {  
      public int max(int [] array
      {  
      int max = 0;    
      for(int i=0; i<array.length; i++ ) {  
         if(array[i]>max) {  
            max = array[i];  
         }  
      }  
      return max;  
   }  
  
   public int min(int [] array) {  
      int min = array[0];  
     
      for(int i = 0; i<array.length; i++ ) {  
         if(array[i]<min) {  
            min = array[i];  
         }  
      }  
      return min;  
   }  
  
   public static void main(String args[]) 
{  
      Scanner sc = new Scanner(System.in);  
      System.out.println("Enter the array range");  
      int size = sc.nextInt();  
      int[] arr = new int[size];  
      System.out.println("Enter the elements of the array ::");  
  
      for(int i=0; i<size; i++) 
      {  
         arr[i] = sc.nextInt();  
      }  
      array m = new array();  
      System.out.println("Maximum value in the array is::"+m.max(arr));  
      System.out.println("Minimum value in the array is::"+m.min(arr));  
 }  

Q: WAP in java to pass any list into function

Ans:
  public static void main(String[] args)
    {
        // Creating an ArrayList Object of Integer type
        ArrayList<Integer> list = new ArrayList<>();
 
        // Inserting some Integer values in ArrayList
        list.add(3);
        list.add(57);
        list.add(7);
 
        // list after insertions : [3, 57, 7]
        // Displaying the ArrayList
        System.out.print("ArrayList after insertions: ");
        display(list);
 
        // Passing the ArrayList as an argument for modification The modifications done to the list inside the function will appear inside the original ArrayList inside main()
        modifyList(list);
 
        // list after modifications : [3, 57, 7, 20, 98]
        // displaying the ArrayList after modifications
        System.out.print("ArrayList after modifications: ");
        display(list);
    }
 
    // Function to modify the arrayList
    public static void modifyList(ArrayList<Integer> parameterList)
    {
        parameterList.add(20);
        parameterList.add(98);
    }
 
    // Function to display the array List
    public static void display(ArrayList<Integer> list)
    {
        System.out.println(list);
    }  

Q: How to add list elements in Map in Java?

import java.util.HashMap;
import java.util.ArrayList;

class HelloWorld {
    public static void main(String[] args) {
        //["id:120", "email:test@test.com", "dept:QA"]
        ArrayList<String> alist = new ArrayList<String>();
        HashMap<String,String> map1 = new HashMap<String,String>();
        alist.add("id:120");
        alist.add("email:test@test.com");
        alist.add("dept:QA");
        
        System.out.println(alist);
        for(String it :alist)
        {
            String[] result = it.split(":");
            map1.put(result[0],result[1]);
        }
      System.out.println(map1);   
}
}

Q: How to find intersection of two array in Java?

Ans:
class Solution 
{
    public int[] intersection(int[] nums1, int[] nums2)
    {
       HashSet<Integer> set1 = new HashSet<Integer>();
        for (Integer n : nums1) 
           set1.add(n);

       HashSet<Integer> set2 = new HashSet<Integer>();
        for (Integer n : nums2) 
          set2.add(n);

        if (set1.size() < set2.size()) 
            return set_intersection(set1, set2);

        else 
            return set_intersection(set2, set1);
    }

    public int[] set_intersection(HashSet<Integer> set1, HashSet<Integer> set2
    {
    int [] output = new int[set1.size()];
    int idx = 0;
    for (Integer s : set1)
      if (set2.contains(s)) 
            output[idx++] = s;

    return Arrays.copyOf(output, idx);
    }
}

Q: What  are different functions of String class in Java?





Q: What are different operations we can do on Array in java?

Ans:

1. Print an array in Java

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);
 
// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d
 
System.out.println(intArrayString);
// [1, 2, 3, 4, 5]

2. Create an ArrayList from an array

String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
System.out.println(arrayList);
// [a, b, c, d, e]

3. Check if an array contains a certain value

String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true

4. Concatenate two arrays

int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

6. Joins the elements of the provided array into a single String

// containing the provided list of elements
// Apache common lang
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c

7. Covnert an ArrayList to an array

String[] stringArray = { "a", "b", "c", "d", "e" };
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));
String[] stringArr = new String[arrayList.size()];
arrayList.toArray(stringArr);
for (String s : stringArr)
System.out.println(s);

8. Convert an array to a set

Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]

9. Reverse an array

int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]

10. Remove element of an array

int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));


Q:What is Custom Exception and how you can implement in java?

Ans:

class InvalidAgeException  extends Exception  
{     
    public InvalidAgeException (String str)  
    {   
        // calling the constructor of parent Exception  
        super(str);  
    }  
}
      
// class that uses custom exception InvalidAgeException  
public class TestCustomException1  
{    
    static void validate (int age) throws InvalidAgeException
{         
                if(age < 18)
{    
        throw new InvalidAgeException("age is not valid to vote");    
    }  
                 Else 
{           
System.out.println("welcome to vote");           
}       
}    
  
    // main method  
    public static void main(String args[])    
    {         
try  
        {       // calling the method   
            validate(13);  
        }  
        catch (InvalidAgeException ex)  
        {              
    System.out.println("Caught the exception");      
            // printing the message from InvalidAgeException object  
            System.out.println("Exception occured: " + ex);  
        }   
        System.out.println("rest of the code...");    
    }  
}  

Q: WAP to replace outer range index as space in string?

Ans:

    public static void main(String[] args) {
        String s = "Dheeraj";
char[] a = s.toCharArray();
char[] news = new char[10];
for(int i=0,k=0;i<a.length;i++)
{
  news[k] = a[i];
  k++;
}
System.out.println(news);
    }


Q: Solution in Java for finding the non repeating characters in a string

Ans: 
class Main
{
    public static void main(String args[])
    {
        String inputStr ="prepinsta";
        boolean flag = true;

        for(char i :inputStr.toCharArray())
        {
            // if current character is the last occurrence in the string
            if (inputStr.indexOf(i) == inputStr.lastIndexOf(i))
            {
                System.out.println("First non-repeating character is: "+ i);
                flag = false;
                break;
            }
        }

        if(flag)
            System.out.println("There is no non repeating character in input string");
    }
}


Q: Find first non-repeating character in a string using hashmap

Ans:
public static void main(String[] args) {
System.out.println("Enter an input string ");
// Take an input
Scanner in = new Scanner(System.in);
String str = in.nextLine();
// Assign length of a string
int len = str.length();

    // HashMap implementation for key and value pair
    HashMap<Character, Integer> charcount = new HashMap<Character, Integer>();
    Character ch;

    /*Create a key and value pair for character and it's count. If there  is no value stored for a character then set it to 1. 
    Else we increment the character value by 1 */
    for(int i = 0; i < len; i++) {
    ch = str.charAt(i);

    /* If character is already exists then increment it's count by 1 */
    if(charcount.containsKey(ch)) 
    {
    charcount.put(ch, charcount.get(ch)+1);
    
    else {
    // If character does not not exist
    charcount.put(ch, 1);
    }
}

for (int j = 0; j < len; j++) 
{
ch = str.charAt(j);
// Check character with value 1 (First non-repeated character)   
if(charcount.get(ch) == 1)
{
System.out.println("First non-repeated character is " + ch);
break;
}

Q:Explain comparable and comparator with java example

Ans:
ComparableComparator
1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price.The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.
2) Comparable affects the original class, i.e., the actual class is modified.Comparator doesn't affect the original class, i.e., the actual class is not modified.
3) Comparable provides compareTo() method to sort elements.Comparator provides compare() method to sort elements.
4) Comparable is present in java.lang package.A Comparator is present in the java.util package.
5) We can sort the list elements of Comparable type by Collections.sort(List) method.We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.

Java Comparable Example  
import java.util.*;  
import java.io.*;  
class Student implements Comparable<Student>
{  
 int rollno;  
 String name;  
 int age; 
 
    Student(int rollno,String name,int age)
    {  
    this.rollno=rollno;  
    this.name=name;  
    this.age=age;  
    }  

    public int compareTo(Student st)
    {  
    if(age==st.age)  
    return 0;  
    else if(age>st.age)  
    return 1;  
    else  
    return -1;  
    }  
 
//Creating a test class to sort the elements  
public class TestSort3{  
public static void main(String args[]){  
ArrayList<Student> al=new ArrayList<Student>();  
al.add(new Student(101,"Vijay",23));  
al.add(new Student(106,"Ajay",27));  
al.add(new Student(105,"Jai",21));  
  
Collections.sort(al);  
for(Student st:al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
}  
}  

Output:

105 Jai 21
101 Vijay 23
106 Ajay 27

Java Comparator Example
Let's see an example of the Java Comparator interface where we are sorting the elements of a list using different comparators.

class Student
{  
 int rollno;  
 String name;  
 int age;  

    Student(int rollno,String name,int age)
    {  
    this.rollno=rollno;  
    this.name=name;  
    this.age=age;  
    }  
 
AgeComparator.java
import java.util.*;  
class AgeComparator implements Comparator<Student>
{  
    public int compare(Student s1,Student s2)
    {  
    if(s1.age==s2.age)  
    return 0;  
    else if(s1.age>s2.age)  
    return 1;  
    else  
    return -1;  
    }  
 
NameComparator.java
This class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic.

import java.util.*;  
class NameComparator implements Comparator<Student>
{  
    public int compare(Student s1,Student s2)
    {  
        return s1.name.compareTo(s2.name);  
    }  
}  

TestComparator.java
In this class, we are printing the values of the object by sorting on the basis of name and age.
import java.util.*;  
import java.io.*;  
class TestComparator
{  
public static void main(String args[])
{  
//Creating a list of students  
ArrayList<Student> al=new ArrayList<Student>();  
al.add(new Student(101,"Vijay",23));  
al.add(new Student(106,"Ajay",27));  
al.add(new Student(105,"Jai",21));  
  
System.out.println("Sorting by Name");  
Collections.sort(al,new NameComparator());  
for(Student st: al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
  
System.out.println("sorting by Age");  
Collections.sort(al,new AgeComparator());   
for(Student st: al){  
System.out.println(st.rollno+" "+st.name+" "+st.age);  
}  
  
}  
}  
Output:

Sorting by Name
106 Ajay 27
105 Jai 21
101 Vijay 23

Sorting by Age       
105 Jai 21
101 Vijay 23
106 Ajay 27

Q:write a java program to shift the array integers to right without vacated positions with zeros

Ans:
public class ArrayShiftRightExample 
{
    public static void main(String[] args) 
{

        //Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};

//n determine the number of times an array should be rotated.
int n = 1;

//Displays original array
System.out.println("Original array: ");
System.out.println(Arrays.toString(arr));

//Rotate the given array by n times toward right
for(int i = 0; i < n; i++)
                       {
    int j, last;
   //Stores the last element of array
   last = arr[arr.length-1];

   for(j = arr.length-1; j > 0; j--)
                           {
       //Shift element of array by one
arr[j] = arr[j-1];
   }

  //Last element of array will be added to the start of array.
  arr[0] = last;
}
System.out.println("Array after right rotation: ");
System.out.println(Arrays.toString(arr));
    }
}
Original array: 
[1, 2, 3, 4, 5]
Array after right rotation: 
[5, 1, 2, 3, 4]

Q: What are multiple ways to iterate or loop a Map in Java.

Ans:
Using foreach in Java 8

If you using Java 8 this is the easiest way to loop the Map.

        Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Jhon");
customers.put(2, "Smith");
customers.put(3, "Sally");

customers.forEach((id, name) -> {System.out.println("Key : " + id + " value : " + name);
});

Using stream() in Java 8

This is also using in Java 8. If you want to filter some data while looping this is one of best way to do that.


        Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Jhon");
customers.put(2, "Smith");
customers.put(3, "Sally");

customers.entrySet().stream().forEach(e ->System.out.println("Key : " + e.getKey() + " value : " + e.getValue())
);

Using entrySet()

    Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Jhon");
customers.put(2, "Smith");
customers.put(3, "Sally");

    for (Map.Entry<Integer, String> entry : customers.entrySet()) 
    {
      System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());
    }

Using keySet()

    Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Jhon");
customers.put(2, "Smith");
customers.put(3, "Sally");

    for (Integer key : customers.keySet()) 
    {
      System.out.println("Key : " + key + " value : " + customers.get(key));
    }

Using iterator through map

    Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Jhon");
customers.put(2, "Smith");
customers.put(3, "Sally");

IIterator<Map.Entry<Integer, String>> iterator = customers.entrySet().iterator();

while (iterator.hasNext()) 
                {
Map.Entry entry = iterator.next();
System.out.println("Key : " + entry.getKey() + " value : " + entry.getValue());
}

Using iterator through the KeySet

 Map<Integer, String> customers = new HashMap<>();
customers.put(1, "Jhon");
customers.put(2, "Smith");
customers.put(3, "Sally");

Iterator<Integer> iterator = customers.keySet().iterator();
while (iterator.hasNext()) 
{
Integer key = iterator.next();
System.out.println("Key : " + key + " value : " + customers.get(key));
}

Q: Is it necessary to put catch statements after a try-block?

Ans:
You need to put either catch or finally block after try.

try {}
finally {}
or
try {}
catch (Exception e) {}

Q : Write a program to sort an array from middle index

Ans:
             int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr,3,7); //it will neglect the 7th index it will be accessed till 6th index only
System.out.println("After sorting :");
for (int num : arr) {
System.out.print(num + " ");
}
O/P:The original array is: 
5 -2 23 7 87 -42 509 
After sorting :
5 -2 23 -42 7 87 509

Q :What is the difference between a normal and functional interface in Java?

Ans:
The normal interface in Java can contain any number of abstract methods, while the functional interface can only contain just one abstract method.
You might be thinking why they are called functional interfaces? Once you know the answer, it might be a little easier for you to remember the concept.
Well, they are called functional interfaces because they wrap a function as an interface. The function is represented by the single abstract method on the interface.
Some examples of the functional interface are Runnable, Callable, Comparator, and Comparable from old API and Supplier, Consumer, and Predicate, etc. from new function API.

// Java program to demonstrate lambda expressions to
// implement a user defined functional interface.
 
@FunctionalInterface
 interface Square {
    int calculate(int x);
}
 
class Test {
    public static void main(String args[])
    {
        int a = 5;
         // lambda expression to define the calculate method
        Square s = (int x) -> x * x;
 
        // parameter passed and return type must be
        // same as defined in the prototype
        int ans = s.calculate(a);
        System.out.println(ans);
    }
}


Q: Java Program to Print any Statement without Using the Main Method

Ans:
class PrintWithoutMain {
  
    // static block
    static
    {
        // prints "Hello World!!" to the console
        System.out.println("Hello World!!");
  
        // exit from the program
        System.exit(1);
    }
}


Q: How to remove all special characters from String ?

Ans:

public static void main(String args[])   
{  
String str= "This#string%contains^special*characters&.";   
str = str.replaceAll("[^a-zA-Z0-9]", " ");  
System.out.println(str);  
}  
Note = [^...]: When the ^ symbol is placed at the beginning inside the square brackets This means that it will match any character not listed in the brackets.

Q: Print highest possible number in given number

Ans:

import java.util.Arrays;
import java.util.Collections;

class HelloWorld {
    public static void main(String[] args) {
       int number = 3456986;

        // Convert the number to a string
        String numberStr = String.valueOf(number);

        // Convert the string to a character array
        Character[] digits = new Character[numberStr.length()];
        for (int i = 0; i < numberStr.length(); i++) {
            digits[i] = numberStr.charAt(i);
        }

        // Sort the digits in descending order
        Arrays.sort(digits, Collections.reverseOrder());

        // Convert the sorted character array back to a string
        StringBuilder highestNumberStr = new StringBuilder();
        for (Character digit : digits) {
            highestNumberStr.append(digit);
        }

        // Convert the string back to a number
        long highestNumber = Long.parseLong(highestNumberStr.toString());

        // Print the highest possible number
        System.out.println("Highest possible number: " + highestNumber);
    }

    }

Q: What is fundamental difference between List, Set and Map ?

Order:

List: Maintains insertion order and allows duplicates.
Set: Does not maintain order (with HashSet) and does not allow duplicates.
Map: Stores key-value pairs and the order depends on the implementation (HashMap does not maintain order, LinkedHashMap maintains insertion order, and TreeMap maintains sorted order).

Duplicates:

List: Allows duplicates.
Set: Does not allow duplicates.
Map: Allows duplicate values but does not allow duplicate keys.

Usage:

List: Use when you need an ordered collection with possible duplicate elements.
Set: Use when you need a collection of unique elements and do not care about order (or need a specific order).
Map: Use when you need to associate values with keys and efficiently look up values by their keys.

Comments