Automation Using Selenium Webdriver

Java Interview Questions for Tester

Interview Questions on oops Concept in Java

Here we cover all topics related to oops concept in java. Once again we discuss some oops concept in detail separately.
What are different oops concept in java ?
OOPs stands for Object Oriented Programming. The oops concepts are similar in any other programming languages. Because it is not programming concept. All oops concept in java are;

  • Class
  • Object
  • Polymorphism
  • Inheritance
  • Abstraction
  • Encapsulation
  • Aggreagation
  • Composition
  • Association

What is class ?

A class is a specification or blue print or template of an object.

What is object ?

Object is instance of class. It is dynamic memory allocation of class.

What are the Characteristics of Object ?

Characteristics of Object are;State Behavior and Identity.

Can a class extend more than one class in Java ?

No, a class can only extend another class because Java doesn't support multiple inheritances but yes, it can implement multiple interfaces.

What is the difference between abstraction and polymorphism in Java ?

Abstraction generalizes the concept and Polymorphism allow you to use different implementation without changing your code.

What is an Abstraction ?

Abstraction is a process to show only usful data and remaining hide from user.

Real Life Example of Abstraction ?

When you log into your email, compose and send a mail. Again there is a whole lot of background processing involved, verifying the recipient, sending request to the email server, sending your email. Here you are only interested in composing and clicking on the send button. What really happens when you click on the send button, is hidden from you.

Real life example of abstraction ?

Real life example of abstraction is ATM machine; here only show balance in your account but not display ATM pin code.

What is Encapsulation ?

The process of binding data and methods into a single unit is known as Encapsulation. In other word The process of binding the data with related methods known as encapsulation.

Real Life Example of Encapsulation ?

Encapsulation is like enclosing in a capsule. 
Encapsulation is like your bag in which you can keep your pen, book etc.

What is inheritance ?

It is used in java for achieve concept of re-usability. As the name suggests , inheritance means to take something that already made.

What is polymorphism ?

It is process to represent any things in multiple forms.

Real life example of Polymorphism ?

A Person who knows more than two languages he can speak in a language which he knows. Here person is Object and speak is polymorphisam.

What is method overloading in Java ?

When same method is available in any class with same name and different signature is called method overloading.

What is method overriding in Java ?

When same method available in base class and drive class with same name and same signature it is called method overriding.

What is Aggregation ?

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship..

What is Composition ?

Composition is the design technique to implement has-a relationship in classes. Composition in java is achieved by using instance variables that refers to other objects.

Can we declare abstract method as final ?

No. its not possible to declare abstract method with final keyword. Because abstract methods should be override by its sub classes.

Is it possible to declare abstract method as private ?

No. its not possible to declare abstract method with private. Because abstract methods should be override by its sub classes.

Differences between method Overloading and method Overriding ?

Overloaded MethodOverridden Method
ArgumentsMust be ChangeMust not be change
Return TypeCan changeCan't change except for covariant returns
ExceptionsCan ChangeCan reduce or eliminate. Must not throw new or broader checked exceptions
AccessCan changeMust not make more restrictive (can be less restrictive)
InvocationReference type determines which overloaded version is selected. Happens at compile time.Object type determines which method is selected. Happens at runtime.

Interview Questions on Constructor in Java

Why use constructor ?

The main purpose of create a constructor is, for placing user defined values in place of default values.

Why constructor not return any value ?

Constructor will never return any value even void, because the basic aim constructor is to place value in the object

Why constructor definition should not be static ?

Constructor definition should not be static because constructor will be called each and every time when object is created. If you made constructor is static then the constructor before object creation same like main method.

Why constructor is not inherited ?

Constructor will not be inherited from one class to another class because every class constructor is created for initialize its own data members.

What is purpose of default constructor ?

The purpose of default constructor is to create multiple object with respect to same class for placing same value.

What is purpose of parameterized constructor ?

The purpose of parametrized constructor is to create multiple object with respect to same class for placing different value of same type or different type or both.

Is constructor inherited?

No, constructor is not inherited.

Can you make a constructor final?

No, constructor can't be final.

What is the purpose of default constructor?

The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.

Can we use both "this" and "super" in a constructor ?

No, because both this and super should be the first statement.

Does constructor return any value?

yes, that is current instance (You cannot use return type yet it returns a value).

What is flow of constructor in Java ?

Constructor are calling from bottom to top and executing from top to bottom.

Why overriding is not possible at constructor level. ?

The scope of constructor is within the class so that it is not possible to achieved overriding at constructor level.

Difference between Method and Constructor

MethodConstructor
1Method can be any user defined nameConstructor must be class name
2Method should have return typeIt should not have any return type (even void)
3Method should be called explicitly either with object reference or class referenceIt will be called automatically whenever object is created
1Method is not provided by compiler in any case.The java compiler provides a default constructor if we do not have any constructor.

Interview Questions on Abstraction in Java

What is Abstraction ?

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

How achieve Abstraction in Java ?

There are two ways to achieve abstraction in java
  • Abstract class (0 to 100%)
  • Interface (100%)

Real life example of Abstraction ?

Mobile phone is one of example of abstraction. We only know about how to call and use mobile but we can't know about internal functionally of mobile phone.

Real life example of Abstraction and Encapsulation ?

Outer Look of a Television, like it has a display screen and channel buttons to change channel it explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen are connect with each other using different circuits , it explains Encapsulation.

Which of the following Java feature show only important information ?

  • Inheritance
  • Encapsulation
  • Abstraction
  • Composition
Ans: Abstraction

Interview Questions on Polymorphism in Java

.

What is Polymorphism ?

The ability to define a function in multiple forms is called Polymorphism.

What is Overloading ?

Whenever several methods have same names with;
  • Different method signature and different number or type of parameters.
  • Same method signature but different number of parameters.
  • Same method signature and same number of parameters but of different type
It is determined at the compile time.

What is method overriding ?

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. It is determined at the run time.

Difference between method overloading and mehtod Overloading ?

Method overloading is determined at the compile time and method overriding is determined at the run time

How to achieve polymorphism in Java ?

How to achieve polymorphism in Java ?

In Java, static polymorphism is achieved through method overloading and method overriding.

Types of polymorphism in Java ?

In Java, there are two types of polymorphism.
  • Compile time polymorphism (static binding or method overloading)
  • Runtime polymorphism (dynamic binding or method overriding)

How to achieve static polymorphism in Java ?

In Java, static polymorphism is achieved through method overloading.

How to achieve dynamic polymorphism in Java ?

In Java, dynamic polymorphism is achieved through method overriding.

What is Compile time polymorphism ?

As the meaning is implicit, this is used to write the program in such a way, that flow of control is decided in compile time itself. It is achieved using method overloading.

Example

public static int add(int a, int b)
{
......
......
}

public static double add(double a, double b)
{
......
......
}

public static float add(float a, float b)
{
......
......
}

What is Runtime polymorphism ?

Run time Polymorphism also known as method overriding and it is achieve at runtime.

Example

class Vehicle
{
   public void move() 
 {
    System.out.println("Vehicles can move !!!!");
  }
}

class MotorBike extends Vehicle 
{
  public void move()
{
 System.out.println("MotorBike can move and accelerate too!!!");
}
}

class Demo {

    public static void main(String[] args)
 {
   Vehicle obj=new MotorBike();
   obj.move();    // prints message MotorBike can move and accelerate too!!!
   obj=new Vehicle();
   obj.move();    // prints message Vehicles can move!!
 }
}

Interview Questions on Interface in Java

What is Interface ?

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface..

Main features of Interface ?

  • Interface cannot be instantiated
  • An interface does not contain any constructors
  • All of the methods in an interface are abstract

Can an Interface be final ?

No, because its implementation is provided by another class.

What is marker interface ?

An interface that have no data member and method is known as a marker interface.For example Serializable, Cloneable etc.

What is difference between abstract class and interface ?

An abstract class can have method body (non-abstract methods) but Interface have only abstract methods.

How to implement Interface in Java ?

Syntax

interface A
{
....
....
}
interface B
{
....
....
}
class C implements A,B
{
....
....
}

Interview Questions on Inheritance in Java

In Java Programming Inheritance is used for reuse features of one class into another class, Using this concept enhance (improve or increase) performance of application.

What is Inheritance ?

Inheritance is one of the main features of any object oriented programming. Using inheritance concept, a class (Sub Class) can inherit properties of another class (Super Class). So it is used for reuse features.

Main advantage of using Inheritance ?

Using this feature you can reuse features, less memory wastage, less time required to develop and application and improve performance of application.

Types of Inheritance supported by Java ?

Java support only four types of inheritance in java.
  • Single Inheritance
  • Multi level Inheritance
  • Hybrid Inheritance
  • Hierarchical Inheritance

Why use Inheritance ?

  • For Code Re usability.
  • For Method Overriding.

What is multilevel inheritance ?

Getting the properties from one class object to another class object level wise with different priorities.

Which of these keyword must be used to inherit a class ?

  • a) super
  • b) this
  • c) extent
  • d) extends
d. extends

What is Multiple Inheritance ?

The concept of Getting the properties from multiple class objects to sub class object with same priorities is known as multiple inheritance.

How Inheritance can be implemented in java ?

Inheritance can be implemented in Java using two keywords, they are;
  • extends
  • Implements
Which of these keywords is used to refer to member of base class from a sub class ?
  • a) upper
  • b) super
  • c) this
  • d) None of these
Answer: b
extends is used for developing inheritance between two classes and two interfaces.
Implements keyword is used to developed inheritance between interface and class.

What is syntax of inheritance ?

Syntax

public class subclass extends superclass
{
//all methods and variables declare here
}

Which inheritance are not supported bb Java ?

Multi Inheritance is not supported by java.

How Inheritance can be implemented in java ?

Inheritance can be implemented in JAVA using these two keywords; extends and implements

How do you implement multiple inheritance in java ?

Using interfaces java can support multiple inheritance concept in java.

Syntax

interface A
{
....
....
}
interface B
{
....
....
}
class C implements A,B
{
....
....
}

How do you implement multiple inheritance in java ?

Using interfaces java can support multiple inheritance concept in java. in java can not extend more than one classes, but a class can implement more than one interfaces.

Why we need to use Inheritance ?

It is used for code re-usability and for Method Overriding.

Can a class extend itself ?

No, A class can't extend itself.

What is syntax of Inheritance ?

Syntax

public class subclass extends superclass
{

//all methods and variables declare here
}

Example of Single Inheritance in Java

Example

class Faculty
{  
float salary=30000;  
}  
class Science extends Faculty
{ 
float bonous=2000;
public static void main(String args[])
{
Science obj=new Science(); 
System.out.println("Salary is:"+obj.salary);  
System.out.println("Bonous is:"+obj.bonous);  
}  
} 

why Java Doesn't Support multiple Inheritance ?

Due to ambiguity problem.

What happens if super class and sub class having same field name ?

Super class field will be hidden in the sub class. You can access hidden super class field in sub class using super keyword.

How do you implement multiple inheritance in Java ?

Example

interface A
{
.....
.....
}
interface B
{
.....
.....
}
class C implements A,B
{
}

Can we reduce the visibility of the inherited or overridden method ?

Ans. No.

Which of the following is tightly bound ? Inheritance or Composition ?

Ans. Inheritance.

Does a class inherit the constructor of its super class ?

Ans. No

Interview Questions on Final Keyword in Java

Where you use final keyword in java ?

Final keyword in java are used at;
  • Final at method level
  • Final at class level
  • Final at variable level

What are final class, final method and final variable ?

  • Final class: can not be extended.
  • Final method: can not be overridden in the sub class.
  • Final class: can not change it’s value once it is initialized.

What is the main difference between abstract method and final method?

Abstract methods must be overridden in sub class where as final methods can not be overridden in sub class

When use final class in java ?

If a class needs some security and it should not participate in inheritance in this situation we need to use final class.

What will happen if we try to extend final class in java ?

Compiler get an error

Can we declare interface as final ?

No, because interface must be implement in other class.

Can we declare constructor as final ?

No, cunstructor can't be final.

What will happen if we try to override final methods in sub classes ?

Compile time error will come :Cannot override the final method from Super class, because you can't override final method in sub class.

Can we create object for final class?

Yes we can create object for final class.

Can we declare constructors as final?

No, constructors can not be final.

What is the use of final keyword in java ?

Final keyword in java is used to make any class or a method or a field as unchangeable. We can't extend final class, not override final method, can't change value of final variable.

Can we change the value of an interface field ?

No, we can't change the value of an interface field. Because interface fields is by default final and static. They remain constant for whole execution of a program.

Interview Questions on This Keyword in Java

What is this keyword ?

this is reference variable that refers to the current object.

Why use this keyword ?

this keyword can be used to refer current class instance variable and this keyword can also be used to return the current class instance.

What are the uses of this keyword in constructor ?

this can be passed as argument in the constructor call.

Can we call methods using this keyword ?

Yes we can use this keyword to call current class non static methods.

Uses of this keyword with constructor ?

Used to invoke current class constructor.

Difference Between this() and super() ?

Super keyword is always pointing to base class features and this keyword is always pointing to current class features.
this is a reference to the current object in which this keyword is used whereas super is a reference used to access members specific to the parent Class.
this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.

What is the difference between this. (this dot) and this() (this off). ?

this. can be used to differentiate variable of class and formal parameters of method or constructor.
this() can be used to call one constructor within the another constructor without creation of objects multiple time for the same class.

What is difference between super(), super(..), this() and this(..) ?

super() and super(..) are used for establishing the communication between base class and derived class constructor.
this() and this(...) are used for establishing the communication between current class constructor.

Interview Questions on Super Keyword in Java

What is super keyword ?

It is used to access members of the base class.

Can we use both "this" and "super" in a constructor ?

No, because both this and super should be the first statement.

What are usage of java super Keyword ?

  • super is used to refer immediate parent class instance variable.
  • super() is used to invoke immediate parent class constructor.
  • super is used to invoke immediate parent class method.

When Need of super keyword ?

Whenever the derived class is inherits the base class features, there is a possibility that base class features are similar to derived class features and JVM gets an ambiguity. In order to differentiate between base class features and derived class features must be preceded by super keyword.

Difference Between this() and super() ?

Super keyword is always pointing to base class features and this keyword is always pointing to current class features.
this is a reference to the current object in which this keyword is used whereas super is a reference used to access members specific to the parent Class.
this is primarily used for accessing member variables if local variables have same name, for constructor chaining and for passing itself to some method whereas super is primarily used to initialize base class members within derived class constructor.

What is difference between super(), super(..), this() and this(..) ?

super() and super(..) are used for establishing the communication between base class and derived class constructor.
this() and this(...) are used for establishing the communication between current class constructor.

In a case where there are no instance variables what does the default constructor initialize ?

Java expects the superclass ( Object Class ) constructor to be called while creation of any object. So super constructor is called in case there are no instance variables to initialize.

Interview Questions on Static Keyword in Java

.

What is static keyword in java ?

Static keyword in java are used for memory management

Why we use static keyword in java ?

Static keyword is mainly used for memory management.

What is static variable in java

Variables declared with static keyword is known as static variables.

What is static variable in java? ?

Variables declared with static keyword is known as static variables. If we change any static variable value using a particular object then its value changed for all objects means it is common to every object of that class. This type of variable is class level.

What is static method in java ?

Method which is preceded with static keyword is know as static method. JVM will not call these static methods automatically you need to call these static methods from main method or static block or variable initialization. These types of method called by using class name itself no need to create object.
Note: Only Main method will b called by JVM automatically.

Example

static void show()
{
......
......
}

What is static block in Java ?

Static blocks are the blocks which will have braces and with static keyword and these block execute at the time of class loading.

Example

static
{ 
......
......
 }

What is the need of static block ?

Static blocks will be executed at the time of class loading. If you want to execute any logic before main method loading you should go with static block.

Why main method is static in java ?

To execute main method without creating object.

.Can we overload static methods in java ?

Yes

Can we override static methods in java ?

No

Can we write static public void main(String [] args) ?

Yes, Order of modifiers can change.

Interview Questions on String Handling in Java

Why use string handling in Java

The basic aim of String Handling concept is storing the string data in the main memory (RAM), manipulating the data of the String, retrieving the part of the String etc. String Handling provides a lot of concepts that can be performed on a string such as concatenation of string, comparison of string, find sub string etc.

Difference between String and StringBuffer

What is difference between equal() and == ?

equals() method always used to comparing contents of both source and destination String. It return true if both string are same in meaning and case otherwise it returns false.
== Operator is always used for comparing references of both source and destination objects but not their contents.
StringStringBuffer
1The data which enclosed within double quote (" ") is by default treated as String class.The data which enclosed within double quote (" ") is not by default treated as StringBuffer class
2String class object is immutableStringBuffer class object is mutable
3When we create an object of String class by default no additional character memory space is created.When we create an object of StringBuffer class by default we get 16 additional character memory space.

When we use String, StringBuffer and StringBuilder

  • If the content is fixed and would not change frequently then we use String.
  • If content is not fixed and keep on changing but thread safety is required then we use StringBuffer
  • If content is not fixed and keep on changing and thread safety is not required then we use StringBuilder

What is Similarities between String and StringBuffer

  • Both of them are belongs to public final. so that they never participates in inheritance that is is-A relationship is not possible but they can always participates in As-A and Uses-A relationship.
  • We can not override the method of String and StringBuffer.

Difference between StringBuffer and StringBuilder

All the things between StringBuffer and StringBuilder are same only difference is StringBuffer is synchronized and StringBuilder is not synchronized. synchronized means one thread is allow at a time so it thread safe. Not synchronized means multiple threads are allow at a time so it not thread safe.
StringBufferStringBuilder
1It is thread safe.It is not thread safe.
2Its methods are synchronized and provide thread safety.Its methods are not synchronized and unable to provide thread safety.
3Relatively performance is low because thread need to wait until previous process is complete.Relatively performance is high because no need to wait any thread it allows multiple thread at a time.
1Introduced in 1.0 version.Introduced in 1.5 version.

What is StringTokenizer ?

It is a pre defined class in java.util package can be used to split the given string into tokens (parts) based on delimiters (any special symbols or spaces).

Interview Questions on Exception Handling in Java

What is Exception Handling ?

The process of converting system error messages into user friendly error message is known as Exception handling.

What is Exception ?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions.

Which is super class for any Exception class ?

Object class is super class for any Exception class.

Can any statement is possible between try and catch block ?

Each and every try block must be immediately followed by catch block that is no intermediate statements are allowed between try and catch block.

Can any try block contain another try block ?

Yes, One try block can contains another try block that is nested or inner try block can be possible.

Can finally block be used without catch ?

Yes but should follow "try" block then.

When IOException is thrown ?

IOException is thrown in following conditions which is given below;
  • Try to transfer more data but less data are present.
  • Try to read data which is corrupted
  • Try to write but file is read only.

When ArithmeticException is thrown ?

The ArithmeticException is thrown when integer is divided by zero or taking the remainder of a number by zero. It is never thrown in floating-point operations.

Difference between throw and throws ?

throwthrows
1throw is a keyword used for hitting and generating the exception which are occurring as a part of method bodythrows is a keyword which gives an indication to the specific method to place the common exception methods as a part of try and catch block for generating user friendly error messages
2The place of using throw keyword is always as a part of method body.The place of using throws is a keyword is always as a part of method heading
3When we use throw keyword as a part of method body, it is mandatory to the java programmer to write throws keyword as a part of method headingWhen we write throws keyword as a part of method heading, it is optional to the java programmer to write throw keyword as a part of method body.

Difference between checked Exception and un-checked Exception ?

Checked ExceptionUn-Checked Exception
1checked Exception are checked at compile timeun-checked Exception are checked at run time
2for checked Exception Extend Throwable class except RuntimeException.for un-checked Exception extend RuntimeException.
3e.g. 
IOException, SQLException, FileNotFoundException etc.
e.g. 
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, NumberNotFoundException etc.

Is it necessary that each try block to be followed by catch block ?

It should be followed by either catch or finally block.

Explain throw, throws , try and catch in Java ?

throw: It is used to re throw an exception.
throws: It is used to declare that the method throws the respective exceptions.
catch: It is used to catch the exception that has been thrown by the respective try block.

Difference between Error and Exception

ErrorException
1Can be handle.Can not be handle.
2Example:
NoSuchMethodError
OutOfMemoryError
Example:
ClassNotFoundException
NumberFormateException

Interview Questions on Multithreading in Java

What is thread ?

Thread is a lightweight components and it is a flow of control. In other words a flow of control is known as thread.

What is multithreading ?

Multithreading in java is a process of executing multiple threads simultaneously.

Explaing State or Life cycle of thread.

State of a thread are classified into five types they are
  • New State
  • Ready State
  • Running State
  • Waiting State
  • Halted or dead State

How to achieve multithreading in java ?

In java language multithreading can be achieve in two different ways.
  • Using thread class
  • Using Runnable interface

Difference between Process and Thread ?

Process is a program in execution whereas thread is a separate path of execution in a program.

In which state no memory is available for thread ?

If the thread is in new or dead state no memory is available but sufficient memory is available if that is in ready or running or waiting state.

Difference between sleep() and suspend() ?

Sleep() can be used to convert running state to waiting state and automatically thread convert from waiting state to running state once the given time period is completed. Where as suspend() can be used to convert running state thread to waiting state but it will never return back to running state automatically.

What is a Deadlock ?

When two threads are waiting each other and can't precede the program is said to be deadlock.

Difference between Serialization and Deserialization ?

Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

What is Thread Synchronization ?

Allowing only one thread at a time to utilized the same resource out of multiple threads is known as thread synchronization or thread safe.

Difference between yield() and sleeping()?

When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.

What is a daemon thread ?

These are threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. garbage collector thread is daemon thread.

Why use Thread Synchronization ?

Whenever multiple threads are trying to use same resource than they may be chance to of getting wrong output, to overcome this problem thread synchronization can be used.

How to achieve Thread Synchronization in java ?

In java language thread synchronization can be achieve in two different ways.
  • Synchronized block
  • Synchronized method

How to achieve multiple inheritance in java ?

Using Interface concept you can achieve multiple inheritance in java.

Difference between suspend() and stop() ?

Suspend method is used to suspend thread which can be restarted by using resume() method. stop() is used to stop the thread, it cannot be restarted again.


Palindrome number algorithm

  • Get the number to check for palindrome
  • Hold the number in temporary variable
  • Reverse the number
  • Compare the temporary number with reversed number
  • If both numbers are same, print "palindrome number"
  • Else print "not palindrome number"
  • class PalindromeExample{  
  •  public static void main(String args[]){  
  •   int r,sum=0,temp;    
  •   int n=454;//It is the number variable to be checked for palindrome  
  •   
  •   temp=n;    
  •   while(n>0){    
  •    r=n%10;  //getting remainder  
  •    sum=(sum*10)+r;    
  •    n=n/10;    
  •   }    
  •   if(temp==sum)    
  •    System.out.println("palindrome number ");    
  •   else    
  •    System.out.println("not palindrome");    
  • }  
  • }  
  • out put:
  • palindrome  number

Factorial Program using loop in java

  1. class FactorialExample{  
  2.  public static void main(String args[]){  
  3.   int i,fact=1;  
  4.   int number=5;//It is the number to calculate factorial    
  5.   for(i=1;i<=number;i++){    
  6.       fact=fact*i;    
  7.   }    
  8.   System.out.println("Factorial of "+number+" is: "+fact);    
  9.  }  
  10. }  
  11. out put:Factorial of 5 is: 120

Prime Number Program in Java

Prime number in Java: Prime number is a number that is greater than 1 and divided 
by 1 or itself. In other words, prime numbers can't be divided by other 
numbers than itself or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime numbers.

  1. class PrimeExample{  
  2.  public static void main(String args[]){  
  3.   int i,m=0,flag=0;    
  4.   int n=17;//it is the number to be checked  
  5.   m=n/2;    
  6.   for(i=2;i<=m;i++){    
  7.    if(n%i==0){    
  8.    System.out.println("Number is not prime");    
  9.    flag=1;    
  10.    break;    
  11.    }    
  12.   }    
  13.   if(flag==0)    
  14.   System.out.println("Number is prime");    
  15. }  
  16. }  
  17. Output:Number is prime

Armstrong Number in Java: Armstrong number is a number that is equal
 to the sum of cubes of its digits for example 0, 1, 153, 370, 371, 407 etc.
Let's try to understand why 153 is an Armstrong number.

  1. 153 = (1*1*1)+(5*5*5)+(3*3*3)  
  2. where:  
  3. (1*1*1)=1  
  4. (5*5*5)=125  
  5. (3*3*3)=27  
  6. So:  
  7. 1+125+27=153

  1. class ArmstrongExample{  
  2.   public static void main(String[] args)  {  
  3.     int c=0,a,temp;  
  4.     int n=153;//It is the number to check armstrong  
  5.     temp=n;  
  6.     while(n>0)  
  7.     {  
  8.     a=n%10;  
  9.     n=n/10;  
  10.     c=c+(a*a*a);  
  11.     }  
  12.     if(temp==c)  
  13.     System.out.println("armstrong number");   
  14.     else  
  15.         System.out.println("Not armstrong number");   
  16.    }  


Compare String with/without using equals() method.



mport java.util.Scanner;

public class CompareString{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the 1st String: ");
        String s1 = in.next();
        System.out.println("Enter the 2nd String: ");
        String s2 = in.next();

        //1st approach without using equals() method
        System.out.println("*********compare  1st String ************");
        if(s1.length()==s2.length()){
            for(int i=0; i<s1.length(); i++){
                if(s1.charAt(i)!=s2.charAt(i)){
                    System.out.println("String "+s1+" is not equal to string "+s2);
                    break;
                }
            }
            System.out.println("String "+s1+" is equal to string "+s2);
        }else{
            System.out.println("String "+s1+" is not equal to string "+s2);
        }

        //2nd approach , just use equals() method
        System.out.println("*********compare 2nd String************");
        if(s1.equals(s2)){
            System.out.println("String "+s1+" is equal to string "+s2);
        }else{
            System.out.println("String "+s1+" is not equal to string "+s2);
        }    
    }
}
OutPut
-------------

Enter the 1st String: 
Selenium Webdriver
Enter the 2nd String: 
Selenium Webdriver
*********compare  1st String************
String Selenium Webdriver is equal to string Selenium Webdriver
*********compare  2nd String************
String Selenium Webdriver is equal to string Selenium Webdriver

Flyod Trinagle


Note- Floyd Triangle is like
1
2 3
4 5 6
7 8 9 10
------------
Code-

import java.util.Scanner;

public class FloydTriangle{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the number of rows which you want in your Floyd Triangle: ");
        int r = in.nextInt();
        int n=0;
        for(int i=0; i<r; i++){
            for(int j=0; j<=i; j++){
                System.out.print(++n+" ");
            }
            System.out.println();
        }
    }
}

Output

Enter the number of rows which you want in your Floyd Triangle: 
5

2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 






2 comments:

  1. Diffference between error Vs exception?
    1) Recovering from Error is not possible. The only solution to errors is to terminate the execution. Where as you can recover from Exception by using either try-catch blocks or throwing exception back to caller.

    2) You will not be able to handle the Errors using try-catch blocks. Even if you handle them using try-catch blocks, your application will not recover if they happen. On the other hand, Exceptions can be handled using try-catch blocks and can make program flow normal if they happen.

    3) Exceptions in java are divided into two categories – checked and unchecked. Where as all Errors belongs to only one category i.e unchecked.

    4) Compiler will not have any knowledge about unchecked exceptions which include Errors and sub classes of RunTimeException because they happen at run time. Where as compiler will have knowledge about checked Exceptions. Compiler will force you to keep try-catch blocks if it sees any statements which may throw checked exceptions.

    5) Exceptions are related to application where as Errors are related to environment in which application is running.

    ReplyDelete
  2. Your all contents are copied from sitesbay.com Within 3 days remove all these contents otherwise i will go with DMCA. Above contents copied from Java Interview Questions

    ReplyDelete