Java For Testers - Interview Q & A
Java For Testers - Interview Q & A
Command Line:
Bijans-MacBook-Pro:java bijan$ javac Sample.java
Bijans-MacBook-Pro:java bijan$ java Sample Java Interview Questions
7) Write a Java program to swap two numbers without using third variable?
public class SwapNumberWithoutVariable {
public static void main(String[] args) {
int x = 10;
int y = 5;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping: " + " x is " + x + " and " + "y is "+ y);
}
}
16) Write a Java program to print stars using for loop, where the number of
stars printed should be equal to the row number?
public class PrintStarPatternInRow {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows");
int rows = sc.nextInt();
printStars(rows);
}
public static void printStars(int n){
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
System.out.print("* ");
}
System.out.println();
}
}
}
20) Write a Java program to demonstrate the usage of break and continue
statements inside while loop?
public class ContinueExample {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 5};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
21) Write a Java program to print the alphabets using for loop?
public class PrintAlphabets
{
public static void main(String[] args)
{
char i;
System.out.printf("The Alphabets from A to Z are: \n");
for (i = 'A'; i <= 'Z'; i++)
{
System.out.printf("%c ", i);
}
}
}
9) How to find whether a String ends with a specific character or text using
Java program?
public class StringEndWith{
public static void main(String args[]) {
String s1 = "Java is a programming language";
//Check if string ends with particular character
boolean endsWithCharacter = s1.endsWith("e");
System.out.println("String ends with character 'e': " + endsWithCharacter);
//Check if string ends with particular text
boolean endsWithText = s1.endsWith("java");
System.out.println("String ends with String 'lang': " + endsWithText);
}
}
13) Write a Java program to remove the spaces before and after the given
string?
class RemoveSpacesInString{
public static void main(String []args){
String s1 = "Interview Questions for Java";
String newString = s1.replaceAll("\\s","");
System.out.println("Old String: " + s1);
System.out.println("New String: " + newString);
}
}
14) Write a Java program to convert all the characters in given string to
lower case?
class ConvertToLowerCase{
public static void main(String []args){
String s1 = "Interview QUESTIONS";
String newString = s1.toLowerCase();
System.out.println("Old String: " + s1);
System.out.println("New String: " + newString);
}
}
16) Write a Java program to find the length of the given string?
class FindLength{
public static void main(String []args){
String s1 = "Interview Questions In Java";
int length = s1.length();
System.out.println("Length of string is: " + length);
}
}
20) Explain the difference between static and instance methods in Java?
Instance method are methods which require an object of its class to be
created before it can be called. Static methods are the methods in Java that
can be called without creating an object of class.
interface A
void display();
{
System.out.println("this is an interface");
t.display();
System.out.println(a);
System.out.println(df.format(now));
long millis=System.currentTimeMillis();
System.out.println(date);
}
4) Write a Java program to demonstrate Date format?
public class GetCurrentDateTime {
System.out.println(sdf.format(date));
System.out.println(sdf.format(cal.getTime()));
System.out.println(dtf.format(now));
System.out.println(DateTimeFormatter.ofPattern("yyy/MM/dd").format(localDate));
int r1 = rand.nextInt(1000);
t1 = null;
System.gc();
t2 = null;
Runtime.getRuntime().gc();
@Override
// Returns the instance of InetAddress containing local host name and address
systemipaddress = sc.readLine().trim();
} catch (Exception e) {
Runtime rs = Runtime.getRuntime();
try{
rs.exec("notepad");
System.out.println(e);
for(int i = 0;i<n;i++){
if(arr[i] == x)
return i;
return -1;
int n = arr.length;
int x = 4;
if(index == -1){
else
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then it can only be present in left subarray
if (arr[mid] > x)
return -1;
int n = arr.length;
int x = 10;
if (result == -1)
else
}
11) Write a Java program to demonstrate Bubble sort?
class BubbleSort
int n = arr.length;
arr[j] = arr[j+1];
arr[j+1] = temp;
int n = arr.length;
System.out.println();
bs.bubbleSort(arr);
System.out.println("Sorted array");
bs.printArray(arr);
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("connected");
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
} catch (Exception e) {
e.printStackTrace();
13) Write a Java program to demonstrate inserting data into a table using
JDBC?
public class InsertIntoDB {
try
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager
stmt = connection.createStatement();
+ "VALUES (1,'John','Smith',5)");
catch (Exception e) {
e.printStackTrace();
}finally {
try {
stmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
try (
){
statement.setString(2, "[email protected]");
statement.execute();
statement.close();
ex.printStackTrace();
}
15) Write a Java program to check Regular Expressions?
class CheckRegularExpression{
Matcher m = pattern.matcher("automation");
while (m.find())
try
catch (Exception e)
}
public class Multithread
object.start();
try {
Thread.sleep(2000);
}
}
exampleThread.start();
exampleThread.join();
18) Write a Java program to write data into the text files?
public static void WriteTextFile() throws IOException
writer.write(fileContent);
writer.close();
19) Write a Java program to read data from the text files?
public class ReadTextAsString
return data;
System.out.println(data);
System.out.println(result);
int a = 100
System.out.println(str);
String s = "10";
String s = "13.6";
System.out.println(result);
String s = "6.54";
System.out.println(result);
String sDate="01/01/2020";
System.out.println(sDate+"\t"+date);
}
}
System.out.println(str);
}
}
System.out.println();
int res = 1;
if (k > n - k)
k = n - k;
res *= (n - i);
res /= (i + 1);
return res;
int n = 7;
printPascal(n);
11) What is the difference between normal class and final class?
Final class cannot be inherited by any other class but normal class can be
inherited by other classes
Arrays.sort(arr);
}
15) Write a Java program for sorting an array?
public class SortArray
Arrays.sort(arr);
Arrays.sort(arr);
}
17) Find how many duplicate values in Array List?
public static Set<Integer> findDuplicates(int[] input) {
if(duplicates.add(input[i])==false){
23) Write a Java program to check whether an year is leap year or not?
public class LeapYear {
System.out.println("Enter a year");
if(num%400 == 0)
return true;
if(num%100 == 0)
return true;
if(num%4 == 0)
return true;
return false;
– if a field is transient its value will not be persisted. On the other hand volatile
keyword can also be used in variables to indicate compiler and JVM that
always read its value from main memory
– transient keyword can not be used along with static keyword but volatile
can be used along with static.
7) What is the keyword used by a Java class to inherit the properties say
variables and methods of another Class?
The keyword used for inheritance is extends.
class A
int i = 0,j = 1;
}
class B
A a1 = new A():
int a = a1.i;
int b = a1.j;
12) What is the difference between default and protected access modifiers
in Java?
A Default member may be accessed only if the Class accessing the member
belongs to the same Package only where as a Protected member can be
accessed (through Inheritance) by a SubClass even if the SubClass is in a
different Package.
13) What is the difference between static and instance variable in Java?
In case of static variable, each and every instance of the class will share the
same variable, so that if you change it in one instance, the change will reflect
in all instances, created either before or after the change.
Instance variables belong to the instance of a class, thus an object. And every
instance of that class (object) has it’s own copy of that variable. Changes
made to the variable don’t reflect in other instances of that class.
14) What is the difference between static and non-static methods in Java?
– A static method can access only static members and can not access non-
static members but a non-static method can access both static as well as
non-static members.
– Static method uses complie time binding or early binding but Non-static
method uses run time binding or dynamic binding.
– A static method cannot be overridden being compile time binding but a
non-static method can be overridden being dynamic binding.
– Static method occupies less space and memory allocation happens once
but a non-static method may occupy more space.
– A static method is declared using static keyword but a normal method is
not required to have any special keyword.
15) What happens when we specify the final non-access modifier with
variables and methods in Java?
A final variable can be explicitly initialized only once. A reference variable
declared final can never be reassigned to refer to a different object.
A final method cannot be overridden by any subclasses. The final modifier
prevents a method from being modified in a subclass.
16) What is the difference between abstract classes and interfaces in Java?
– Type of methods: Interface can have only abstract methods. Abstract class
can have abstract and non-abstract methods.
– Final Variables: Variables declared in a Java interface are by default final.
An abstract class may contain non-final variables.
– Type of variables: Abstract class can have final, non-final, static and non-
static variables. Interface has only static and final variables.
– Implementation: Abstract class can provide the implementation of
interface. Interface can’t provide the implementation of abstract class.
– Inheritance vs Abstraction: A Java interface can be implemented using
keyword “implements” and abstract class can be extended using keyword
“extends”.
– Multiple implementation: An interface can extend another Java interface
only, an abstract class can extend another Java class and implement
multiple Java interfaces.
– Accessibility of Data Members: Members of a Java interface are public by
default. A Java abstract class can have class members like private, protected,
etc.
17) What is the keyword used for inheriting the interfaces in Java?
Extends keyword is used for inheriting the interfaces.
class A
int i = 0,j = 1;
class B
{
//Accessing variables of class A by creating an instance of the class A
A a1 = new A():
int a = a1.i;
int b = a1.j;
class A
int i = 0,j = 1;
class B
A a1 = new A():
int a = a1.i;
int b = a1.j;
22) What are the predefined methods of HashMap, which are used for
adding the value and retrieving the value in Java?
get – It is used to retrieve or fetch the value mapped by a particular key.
put – It is used to insert a particular mapping of key-value pair into a map.
23) What will this Java code print: String x = “Latest version”; String y = “of
Selenium”; int z = 3; System.out.println(“We are learning Selenium”+” and
the “+x+” “+y+” is “+z); ?
Output – We are learning Selenium and the Latest version of Selenium is 3
4) Can you access the private method from outside the class?
No. Private method cannot be accessed outside the class.
Arraylist to Array:
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
10) What is the difference between String array and Char array?
– String refers to a sequence of characters represented as a single data type.
Character Array is a sequential collection of data type char.
– Strings are immutable. Character Arrays are mutable.
– Strings can be stored in any any manner in the memory. Elements in
Character Array are stored contiguously in increasing memory locations.
– All Strings are stored in the String Constant Pool. All Character Arrays are
stored in the Heap.
doc.getDocumentElement().normalize();
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Statement st = con.createStatement();
int m = st.executeUpdate(sql);
fileInputStream.close();
11. Write a Java program to calculate the power of a number using a while
loop?
public class Power {
public static void main(String[] args) {
long result = 1;
while (exponent != 0)
result *= base;
--exponent;
int sum = 1;
if (n % i==0)
if(i * i != n)
sum = sum + i + n / i;
else
sum = sum + i;
if (sum == n && n != 1)
return true;
return false;
if (isPerfect(n))
System.out.println( n +
}
15. Write a Java program for printing the Fibonacci series from 1 to 10?
class FibonacciNumber
int f1 = 0, f2 = 1, i;
if (n < 1)
return;
System.out.print(f2+" ");
f1 = f2;
f2 = next;
printFibonacciNumbers(10);
int num3 = 7;
else
17. Find and print the largest two numbers from an array of given numbers?
public class LargestTwoNumbers
int n = scn.nextInt();
array[i] = scn.nextInt();
largest1 = array[0];
largest2 = array[1];
temp = largest1;
largest1 = largest2;
largest2 = temp;
largest2 = largest1;
largest1 = array[i];
largest2 = array[i];
18. In the given String, remove the white spaces, reverse it and print only the
odd position characters?
public Class PrintOddChars{
for(int i=0;i<reversedString.length();i++){
if(i%2!=0){
System.out.println(odd);
String rev="";
for(int i=arr.length-1;i>=0;i--)
if (s1.length() != s2.length()) {
status = false;
} else {
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
if (status) {
} else {
}
}
System.out.println(nameCapitalized);
}
public static Map<Character,Integer> findFrequency(String input){
for(char c: arr){
if(frequency.containsKey(c)){
frequency.put(c,frequency.get(c) + 1);
else{
frequency.put(c,1);
return frequency;
22. Find the duplicate strings in a given statement and remove them?
public class RemoveDuplicateWords
for(int i=0;i<words.length;i++)
{
if(words[i]!=null)
for(int j=i+1;j<words.length;j++)
if(words[i].equals(words[j]))
words[j]=null;
for(int k=0;k<words.length;k++)
if(words[k]!=null)
System.out.println(words[k]);
System.out.println(arrSplit[i]);
24. Find and remove the duplicate characters from a given string and print ?
public static String removeDuplicates(String word){
char ch = word.charAt(i);
if (chars.add(ch)) {
output.append(ch);
return output.toString();
printFloydTriangle(rows);
int number = 1;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
number++;
System.out.println();
6) Can we achieve method overloading when the two methods have only
difference in return type?
No. The compiler will give error as the return value alone is not sufficient for
the compiler to figure out which function it has to call. Only if both methods
have different parameter types (so, they have different signature), then
Method overloading is possible.
10) What is super and final keywords in Java and the difference between
them?
Super is a keyword of Java which refers to the immediate parent of a class
and is used inside the subclass method definition for calling a method
defined in the superclass. A superclass having methods as private cannot be
called. Only the methods which are public and protected can be called by the
keyword super. It is also used by class constructors to invoke constructors of
its parent class.
Final is a keyword in Java that is used to restrict the user and can be used in
many respects. Final can be used with:
– Class
– Methods
– Variables
11) Explain run time polymorphism and compile time polymorphism with
examples?
– Compile time Polymorphism: It is also known as static polymorphism. This
type of polymorphism is achieved by function overloading or operator
overloading.
class OverloadedMethods {
return a * b;
}
return a * b * c;
class Main {
System.out.println(MultiplyFun.Multiply(5,2));
System.out.println(MultiplyFun.Multiply(1,4,6));
Output:
10
24
class Parent {
void Print()
System.out.println("parent class");
}
void Print()
System.out.println("subclass1");
class TestPolymorphism {
Parent a;
a = new subclass1();
a.Print();
Output: subclass1
Ex-
Test.print();
Test.print(10);
Output:
Test.print() called
Test.print(int) called
int color;
// An abstract function
abstract void draw();
Interface can have only abstract methods. Abstract class can have abstract
and non-abstract methods.
21) Can we use private and protect access modifiers inside an Interface?
Java interfaces are meant to specify fields and methods that are publicly
available in classes that implement the interfaces. Therefore you cannot use
the private and protected access modifiers in interfaces.
5) What is generics?
Generics enable types (classes and interfaces) to be parameters when
defining classes, interfaces and methods. Much like the more familiar formal
parameters used in method declarations, type parameters provide a way for
you to re-use the same code with different inputs.
6) What is synchronization?
Synchronization in java is the capability to control the access of multiple
threads to any shared resource. Java Synchronization is better option where
we want to allow only one thread to access the shared resource.
11) What are the types of assertion and what are assertion in java?
An assertion allows testing the correctness of any assumptions that have
been made in the program. Assertion is achieved using the assert statement
in Java. While executing assertion, it is believed to be true. If it fails, JVM throws
an error named AssertionError. It is mainly used for testing purposes during
development.
14) In public static void main(String arr[])… what if i replace public with
private ……….. remove static ……..replace void with string?
If we replace public with private then JVM will be unable to access/locate the
main method.
If we remove static than JVM cannot invoke it without instatiating class.
If we replace void with String, it will give compilation error as an unexpected
return value.
15) In hash map we have (key and value ) pair , can we store inside a value
=(key, value ) again ?
Yes. We can store key/value inside a value.
16) What are variable scope in java (in class , in method , in static block)?
– Each variable declared inside a class with private access modifier but
outside of any method, has class scope. As a result, these variables can be
used everywhere in the class, but not outside of it.
– When a variable is declared inside a method, it has method scope and it
will only be valid inside the same method.
– Variables declared inside a block are accessible only inside of that block.
17) Write a Java program so that when ever you create a object, you get to
know how many object u have created?
// Java program Find Out the Number of Objects Created of a Class
class FindCreatedObjects {
noOfObjects += 1;
public Test()
public Test(int n)
public Test(String s)
super.setLicensePlate(license);
24) What is the base class for all java classes? And mention its methods?
The Object class is the parent class of all the classes in java by default.
Following are different methods of Object class:
– getClass(): returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.
– hasCode(): returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.
– equals(Object obj): compares the given object to this object.
– toString(): returns the string representation of this object.
this.first = first;
this.last = last;
return false;
Name n = (Name)o;
Ex-
class ClassName {
// variables
// methods
}
5) What is the command used in Java for exiting the system from current
execution?
The java.lang.System.exit() method exits current program by terminating
running Java virtual machine. This method takes a status code.
6) What is the method from which Java Programs starts execution?
A Java program starts by executing the main method of some class.
– Singleline comments: The single line comment is used to comment only one
line.
– Multiline comments: The multi line comment is used to comment multiple
lines of code.
– Documentation comments: The documentation comment is used to create
documentation API. To create documentation API, you need to use javadoc
tool.
10) What are the different things required for storing data in Java?
– Stack Memory
– Heap Memory
– External data source
11) What is the different data types in Java and what is their purpose?
Data types are divided into two groups:
Primitive data types – includes byte, short, int, long, float, double, boolean and
char
Non-primitive data types – such as String, Arrays and Classes
15) What is the difference between while and do..while loop in Java?
If the condition in a while loop is false, not a single statement inside the loop is
executed. In contrast, if the condition in ‘do-while’ loop is false, then also the
body of the loop is executed at least once then the condition is tested.
17) What is the keyword to be used in Java while declaring methods, when
the method don’t have anything to return?
Void() can be used for methods which don’t return anything.
if(arr[i] == arr[j])
System.out.println(arr[j]);
22) How to find the smallest and largest numbers in a Java Array?
public class FindLargestSmallestNumber {
//numbers array
largest= numbers[i];
24) Write a Java program to swap two strings without using temp or third
variable?
class SwapNumber {
int x = 10;
int y = 5;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swaping:"
}
}
9) try block has exit method, catch block has exception and finally block is
returning an int value. Can you explain the flow of execution?
It will exit the try block and skip the catch block. Then it will execute finally
block to return int value.
10) Have you ever come across conflict in code. How do you resolve?
To resolve a merge conflict caused by competing line changes, you must
choose which changes to incorporate from the different branches in a new
commit.
15) Can we have multiple catch blocks in try catch statements in Java?
Yes we can have multiple catch blocks in try catch statements in Java.
17) How do you know when to use abstract class and Interface?
If the functionality we are creating will be useful across a wide range of
disparate objects, use an interface. Abstract classes should be used primarily
for objects that are closely related, whereas interfaces are best suited for
providing a common functionality to unrelated classes.
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("C:\\sample.txt"));
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
ex.printStackTrace();
20) Is it mandatory to have the same name for Class name and Java file ?
While writing a java program first it is saved as a “.java” file, when it is
compiled it forms byte code which is a “.class” file
this.name = name;
this.regNo = regNo;
return name;
return regNo;
s.append(Character.toUpperCase(str.charAt(i)));
else
s.append(str.charAt(i));
ch = str.charAt(i);
return s.toString().trim();
if (!set1.add(str)) {
set2.add(str);
return set2;
country1.put("Japan", "Tokyo");
country1.put("China", "Beijing");
country2.put("Japan", "Tokyo");
country2.put("China", "Beijing");
if(country1==country2){
return true;
} else
return false;
}
4) Write a Java program to demonstrate creating an Array?
int[] arr;
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
if (str == null) {
return null;
char[] ch = str.toCharArray();
int i = 0;
if (Character.isDigit(ch[i])) {
i++;
} else {
sb.append(ch[i]);
i++;
return sb.toString();
return outputString;
}
7) Java program: Find the count of each element in a two dimensional
matrix?
mp.put(a[i][j], 1);
int count = 0;
if (mp.containsKey(z[j]))
count += 1;
if(arr[i] == arr[j])
System.out.println(arr[j]);
prop.setProperty("db.url", "localhost");
prop.setProperty("db.user", "mkyong");
prop.setProperty("db.password", "password");
prop.store(outputStream, "");
prop.load(inputStream)
prop.getProperty("db.url");
prop.getProperty("db.user");
prop.getProperty("db.password");
prop.keySet();
}
10) Write a Java program to demonstrate creating factorial of a number using
recursion?
if (n == 0)
return 1;
else
return(n * factorial(n-1));
int i,fact=1;
int number=4;
fact = factorial(number);
if(occurrences.containsKey(word)){
} else {
map.put(word,1);
int n1=0,n2=1,n3,count=5;
System.out.print(n1+" "+n2);
for(int i=2;i<count;i++)
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}}
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
class ArrayListExample {
int n = 5;
arrList.add(i);
System.out.println(arrList);
arrList.remove(3);
System.out.println(arrList);
}
15) Write a Java program to demonstrate LinkedList?
list.add("A");
list.add("B");
list.addLast("C");
list.addFirst("D");
list.add(2, "E");
System.out.println(list);
list.remove("B");
list.remove(3);
list.removeFirst();
list.removeLast();
System.out.println(list);
class ArrayListWithListInterface {
public static void main(String[] args)
arrayList.add("Java");
arrayList.add("C#");
arrayList.add("Python");
System.out.println(arrayList);
class HashSetExample{
hs.add("India");
hs.add("Australia");
hs.add("South Africa");
hs.add("India");
System.out.println(hs);
linkedset.add("A");
linkedset.add("B");
linkedset.add("C");
linkedset.add("D");
System.out.println(linkedset);
class TreeSetExample {
ts1.add("A");
ts1.add("B");
ts1.add("C");
ts1.add("C");
System.out.println(ts1);
}
}
class PriorityQueueExample {
pQueue.add(10);
pQueue.add(20);
pQueue.add(15);
System.out.println(pQueue.peek());
System.out.println(pQueue.poll());
class HashMapExample{
h1.put(1,"Java");
h1.put(2,"C#");
h1.put(3,"Python");
System.out.println(h1);
map.put("one", "www.gmail.com");
map.put("two", "www.ymail.com");
map.put("four", "www.outlook.com");
System.out.println(lhm);
class TreeMapExample{
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
class HashtableExample{
hm.put(100,"Jeorge");
hm.put(102,"Smith");
hm.put(101,"Sarah");
hm.put(103,"John");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
25) Write a Java program to demonstrate creating Multidimensional array?
class MultiExample {
int[][] arr = { { 1, 2 }, { 3, 4 } };
+ arr[i][j]);
int c = 2;
int num = 1;
for(int i=1;i<7;i++){
num = sum;
c++;
int[] a = {9,3,6,8,4,7};
for(int i=a.length-1;i>=0;i--){
System.out.println(a[i]);
String[] a = {"One","Two","Three","Four"};
for(int i=0;i<a.length;i=i+2){
System.out.println(a[i]);
}
4) Write a Java program to find the greatest number in an integer array
int[] a = {9,3,6,4,8,5} ?
public class MaxNumber {
Integer[] a = {9,3,6,4,8,5};
System.out.println(max);
5) Write a Java program to find the least number in an integer array int[] a
= {9,3,6,4,8,5} ?
public class MinNumber {
Integer[] a = {9,3,6,4,8,5};
System.out.println(min);
6) What is the predefined variable of Arrays, which can be used to find the
size of the arrays?
length variable can be used to find the size of the arrays.
7) Provide an example for using for loop with single dimensional arrays?
public class ForLoopInArray {
Integer[] a = {9,3,6,4,8,5};
for(int i=0;i<a.length-1;i++)
System.out.println(a[i]);
Integer[] a = {9,3,6,4,8,5};
for(int arr: a)
System.out.println(arr);
9) What are the different access modifiers in Java and explain each of
them?
Following are different access modifiers in Java:
– private: Methods and variables declared as private can only be accessed
within the same class in which they are declared
– protected: Methods and variables declared as protected can only be
accessed within the same package or sub classes in different package
– public: Methods and variables declared as public can be accessed from
anywhere
– default: Methods and variables which are not declared using any access
modifier are accessible within the same package
10) How to find the length of the String without using length function?
public class FindLengthOfString {
String s = "qascript";
int i = 0;
for(char c: s.toCharArray())
i++;
System.out.println(i);
11) How to find out the part of the string from a string?
We can use the substring function to find a part of the string from a string.
Ex –
String str = “QASCRIPT”;
System.out.println(str.substring(2));
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
numbers.add(5);
numbers.add(65);
numbers.add(76);
numbers.add(5);
numbers.add(4);
numbers.add(33);
numbers.add(4);
numbers.add(34);
numbers.add(232);
numbers.add(3);
numbers.add(2323);
System.out.println(maxNumber);
}
14) What is String class and its methods?
String class has many methods to perform different operations on a string.
Some of the methods are:
– length()
– charAt()
– substring()
– concat()
– indexOf()
– trim()
– replace()
17) What’s the difference between a Maven project and a Java project?
In a Java project we need to manually download and configure the jar files.
But in Maven project all project dependencies can be downloaded by
including them in the POM.xml file.
FileReader fr;
int c=0;
try {
fr = new FileReader("src/main/resources/File.txt");
while((c=fr.read())!= -1){
System.out.print((char) c);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
19) Why do we provide “//” in java while fetching a path of excel?
Double backslash is provided in java to avoid compiler interpret words for
system directories