Full notes Download Click Below
(DOWNLOAD)
HR
Interview questions for Fresher
1) Tell me about yourself
My name is alimarP. I am from Haryana. I have done Bachelor of
Technology from the stream of Computer Science and Engineering. I did my academic
project on updated technology like machine learning and data mining. I am good
at Java and C programming language. As my family background is considered, we
are 4 in number. My father is a sweet shop merchant, my mother is a homemaker
and I have one sibling. My strength is that I am a self-learner & have a
positive mind. My weakness is, I don't take rest until my work is finished.
2) Why should I hire you?
As fresher, I don't have any
experience. If you hire me, it is a great opportunity for me to learn something
new and achieve my goals. This is only possible if you hire me and I assure you
that I will give my best to this company.
3) What is your Strength and Weakness?
Strength: I am Honest,
Sincere, Responsible, and have positive Attitude.
Weakness: I don't take
rest until my work finished.
4) Why do you want to work for our company?
It is a great honor for me to work in
a reputed company likes yours because it is a great multinational company. It
has many branches across the world. Employee satisfaction is good in your
company. It's a good platform for me to improve my talent and enhance my skill
and knowledge.
5) What is the difference between Confidence and Over-Confidence?
Confidence means I will win and Overconfidence
means I will win at all the time.
6) What is the difference between Hard-work and Smart work?
Hard work is very necessary for your
life because, without practice, you can?t be able to do smart work.
7) How do you feel about working night and weekends?
If the company needs me then I am
ready to work at any time.
8) Can you work under Pressure?
Yes, it is a Great Honor for me to
work in a presumed organization like yours on the grounds that it is an
incredible multinational organization. It has numerous branches over the world.
Worker fulfillment is great in your organization. It's a decent stage for me to
stand my ability and upgrade my expertise and knowledge.
9) What is your goals?
My short term goal is to be a part of
your company and my long-term goal is to be successful in every parameter of
this company.
10) Would you lie for the company?
If my lie is for the company welfare,
I can but it should not hurt others.
11) How much salary do you expect?
I can expect something which I can
meet my expenses.
12) Where do you see yourself five years now?
I can see myself growing with this
company and reaching a position where I become a valuable asset to this
organization.
Ans 2 : I will see myself in a respectful position in your
company.
13) On the scale of one to ten, rate me as an interviewer.
Sir, you are more educated, more
talented, more experienced than me I am not on a level to judge you.
14) Who has inspired you in your life and why?
My father is my inspiration because
he still shows me the path from nothing to everything. He always guides me to
achieve success in every matter of my life. He is also my best friend because
he even suggested to me as a friend when I make a mistake.
15) What do you know about
our company?
Infosys Limited is an Indian company. The headquarters are in
Bengaluru, Karnataka, India. Company trade name as "Infosys Technologies
Limited." This business provides consulting, information technology and
outsourcing services.
16) Introduce yourself and say something
apart from your Resume.
I would like to tell you other than what is there in it. I am
born and raised in Banaras city. In Banaras, there are not many good colleges
to pursue B.Tech, so I came to Bengaluru for learning and understanding things.
Here, in my early phase I started facing few difficulties but after some days,
I was able to sort out almost every problem. I think, adaptability, quick
learning and problem-solving are my positive points and coming to my weakness I
am emotional kind of person, but this might be helpful in maintaining the
proper relationship.
17) Where would you like to work: software development or software
testing?
Note: Answer depending upon the choice of the person giving the
interview.
Example
1: I
would like to work in software development.
Example
2: I
would like to work in software testing.
18) How do you get to know about our
company?
Note: The interviewee should not lie while answering such
questions. Because an interviewer is a smart person and they can detect it if
you are lying.
Example: I get to know
about your company from several online websites.
19) Why have you applied at Infosys?
Infosys is the second-largest revenue earning IT Company in
India. Every person wants to work for your company.
20) Why do you think you are fit for our
organization?
I am a hard working person, and my priority is to serve your
organization. I can sort out almost every problem, and I think adaptability,
quick learning and problem-solving are my positive points.
21) Do you have an offer from any other
organization?
Note: Interviewee should not lie while answering to such
questions because interviewer can investigate.
Yes, I had many offers from many IT companies like HCL and TCS.
22) Tell us about Infosys and its positioning as compared to its competitors? (Change company name)
Infosys Limited is an Indian company. The headquarters
are in Bengaluru, Karnataka, India. Company trade name as "Infosys
Technologies Limited." This company provides consulting, information
technology and outsourcing services.
Infosys has many competitors, providing the
software facilities worldwide. HCL, Wipro, IBM, and Microsoft were some
software companies in competition with Infosys.
23) You had to wait for 5 hours for the
interview. Are you feeling tired?
Note: This type of questions were asked by the interviewer to
check your patience level and willing to work in the company.
Example: "No. This is
my dream company so wait doesn't matter. I have enough time for the
interview."
24) Tell me how your online test was?
Note: This type of question asked by the interviewer to check
your confidence level for the online test.
Ans : "Online test was good."
25) What is your father's occupation?
What is his job location?
Note: Answer to this question depends on the interviewee
personal information. Every father might have different occupation and
designation.
For
Example, My father is a farmer. (working in my village).
26) Who is your role model? What have you
incorporated into your life from him/her?
Example: The role model of
my life is my mother. Whenever I am down my mother helps me to push my limits,
and she always keeps me on the track. She scolds me every time when I do
something wrong. She is everything for me, and I always got inspired from her
how she manages every problem in every situation.
27) Where do you live?
Note: Answer to this question depends on the interviewee
personal information.
Example
1: I
am living with my family in New Delhi.
Example
2: I
am living in a hostel of Hyderabad.
28) What functional/technical areas you
have interest? Would you be passionate to work? Why?
Example: Technically, I am
active in programming, and I will be passionate to work on my programming
skills because programming is nothing but just telling the computer how to
perform tasks.
29) What about your weaknesses and
strengths? How will you overcome your weaknesses?
Note: While answering such a question, the interviewee should be
very careful. Because disclosing too much weakness will make fewer chances of
being selected.
Example: I can sort out
almost every problem, and I think adaptability, quick learning and
problem-solving are my positive points and coming to my weakness I am emotional
kind of person, but this might be helpful in maintaining the proper
relationship.
30) What Four things would make a good
leader?
The three things would make a good leader are listed below:
- Have Faith in Their Beliefs
- Earn the Respect of the Team
- Make the Hard Choice
- Being close to your team members.
31) What is the success?
Success refers to the accomplishment of an aim or purpose.
32) Tell me one real-time situation where
you have emerged as a Leader?
Example
1: I
don't have any work experience, so I have no such real-time situation when I
have emerged as a leader but, in my college, I have been the leader of the
group project. In my team, I have emerged as a leader.
33) What makes you stand out against all
the other candidates?
I understand that success is not always guaranteed but there is
still hope, and I never lose the faith, whether I succeed or not. I think this
power makes me standalone from all other candidates.
34) What is your ultimate goal in life?
My goal is to work for
the company like Infosys( present interview company name) where I can enhance
my technical skills and knowledge, and my long-term goal is to see myself at a
topmost position in a reputed company like yours.
35) Which personal attributes do you
have?
- I always stay positive.
- I hold a positive attitude
towards all my elders and Youngers.
36) Where do you rate yourself as an
engineer?
I will rate myself 7 out of 10 as an engineer because there are
always some things which have to learn in life.
37) What is your strong point regarding technical knowledge? Like
JAVA, C, C++.
My strongest point of technical knowledge is programming. I like
every programming language because programming is as easy as telling someone to
perform some task, for that you need the same communication language. The only
difference is we are telling task to the computer instead of the humans.
38) Do you have any question for us?
Note: When the interviewers ask this "do you have any
question." Most of the candidates say no. It is a wrong practice.
Candidates should ask questions also according to the situation, and it shows
that you are listening correctly and have a keen interest. Asking questions
also gives you an opportunity to find the right place for you in the company.
But always remember that it should not look artificial.
39) Tell me something about your
short-term and long-term goals.
My short-term goal is to be a part of your organization and my
long-term goal is to be successful in every parameter of this company.
40) What makes you angry?
I get angry when the work given to me is not done on time.
JAVA INTERVIEW QUESTIONS
Ans:-Java is a high-level programming language originally developed
by Sun Microsystems and released
in 1995. Java runs on a variety of platforms, such as Windows,
Mac OS, and the various
versions of UNIX.
2.What are the supported
platforms by Java Programming Language?
Ans:- Java runs on a variet
atforms, such as Windows,
Mac OS, and the various versions of UNIX/Linux like HP-Unix, Sun Solaris, Redhat Linux, Ubuntu,
CentOS, etc.
3.List any five features of Java?
Ans:-Some features include Object Oriented,
Platform Independent, Robust, Interpreted, Multi-threaded Why is Java Architectural Neutral?
It’s compiler generates
an architecture-neutral object file format,
which makes the compiled code to
be executable on many processors, with the presence of Java runtime
system.
4.How Java enabled
High Performance?
Ans:-Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode,
which is a program that contains instructions that must be interpreted into instructions that can be sent directly
to the processor.
5.Why Java is considered dynamic?
Ans:- It is designed
to adapt to an evolving
environment. Java programs
can carry extensive
amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
6.What is Java Virtual Machine and how it is considered in context
of Java’s platform independent feature?
Ans:- When Java is compiled, it is not compiled into
platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine
JVM on whichever platform
it is being run.
7.List two Java IDE’s? Ans:- Netbeans, Eclipse,
etc.
8.List
some Java keywordsunlikeC, C + + keywords? Ans:- Some Java keywords
are import, super,
finally, etc.
9.
What do you mean by Object?
Ans:- Object is a runtime entity and it’s state is
stored in fields and behavior is shown via methods. Methods operate on an object's internal
state and serve as the primary mechanism for object-to- object communication.
10.Define class?
Ans:- A class is a blue print from which individual
objects are created.
A class can contain fields and methods
to describe the behavior of an object.
11.What kind of variables a class can consist of?
Ans:- A class
consist of Local variable, instance variables
and class
12.variables. What
is a Local Variable?
Ans:- Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within
the method and it will be destroyed when the method has completed.
13.What is a Instance
Variable?
Ans:- Instance variables are variables within a class but outside
any method. These variables are instantiated when the class is loaded.
14.What is a Class Variable?
Ans:- These are variables
declared with in a class, outside any method, with the static
15.keyword. What is Singleton class?
Ans:- Singleton class control object creation, limiting
the number to one but allowing the flexibility to create more objects
if the situation changes.
16.What do you mean by Constructor?
Ans:- Constructor gets invoked
when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler
builds a default constructor
for that class.
17.List the three steps for creating an Object for a class?
Ans:- An Object is first declared,
then instantiated and then it is
18.initialized. What is the default value of byte datatype in Java?
Ans:- Default value of byte datatype is 0.
19.What
is the default value of float and double datatype in Java?
Ans:- Default value of float and double datatype in different as compared to C/C++. For float its 0.0f and for double it’s 0.0d
20.When a byte datatype is used?
Ans:- This data type is used to save space in large arrays,
mainly in place of integers,
since a byte is four times smaller
than an int.
21.What is a static variable?
Ans:- Class variables also known as static variables
are declared with the static keyword in a class,
but outside a method, constructor or a block.
22.What do you mean by Access Modifier?
Ans:- Java provides access modifiers to set access
levels for classes, variables, methods and constructors. A member has package or default accessibility when no accessibility modifier is specified.
23.What is protected
access modifier?
Ans:- Variables, methods and constructors which are declared
protected in a
superclass can be accessed
only by the subclasses in other package or any class within the package of the protected members' class.
24.What do
you mean by synchronized Non Access Modifier?
Ans:- Java provides these modifiers for providing functionalities other than Access Modifiers, synchronized used to indicate
that a method can be accessed by only one thread at a time. According to Java Operator
precedence, which operator
is considered to be with highest
precedence?
Postfix operators i.e [] . is at the highest precedence.
25.Variables used in a switch statement
can be used with which datatypes?
Ans:- Variables
used in a switch statement can only be a byte, short, int, or char.
26.
When parseInt method
can be used?
Ans:- This method
is used to get the primitive
data type of a certain String.
27. Why is String class considered immutable?
Ans:- The String class is immutable,
so that once it is created a String object cannot be changed. Since
String is immutable it can safely be shared between many threads ,which
is considered very important for multithreaded programming.
28.Why is StringBuffer called mutable?
Ans:- The String class is considered
as immutable, so that once it is created a String object cannot be changed.
If there is a necessity to make alot of modifications to Strings of characters
then StringBuffer should be used.
29.What is the difference between StringBuffer and StringBuilder class?
Ans:- Use StringBuilder whenever
possible because it is faster
than StringBuffer. But, if thread safety
is necessary then use StringBuffer objects.
30.Which package is used for pattern
matching with regular expressions?
Ans:- java.util.regex package
is used for this purpose.
31.Java.util.regex consists
of which classes?
Ans:- java.util.regex consists of three classes − Pattern
class, Matcher class and PatternSyntaxException class.
32.What is finalize method?
Ans:- It is possible to define a method that will
be called just
before an object's final destruction by the garbage collector. This method is called finalize, and it can be used to
ensure that an object terminates cleanly.
33.What is an Exception?
Ans:- An exception is a problem
that arises during the execution
of a program. Exceptions are caught by handlers positioned along the thread's method
invocation stack.
34.What do you mean by Checked Exceptions?
Ans:- It is an exception that is typically a user error
or a problem that cannot be foreseen by the programmer.
For example, if a file is to be opened, but the file cannot be found, an
exception occurs. These exceptions cannot
simply be ignored at the time of compilation.
35.Explain Runtime Exceptions?
Ans:- It is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation.
36.Which are the two subclasses under Exception class?
Ans:- The Exception class has two main subclasses : IOException class and Runtime Exception Class. When throws
keyword is used?
If a method does not
handle a checked exception, the method must declare it using the
Throws keyword. The throws keyword
appears at the end of a method's
signature.
37.When throw
keyword is used?
Ans:- An exception can be thrown,
either a newly instantiated one or an exception that you just caught, by using throw keyword.
38.How finally used under Exception
Handling?
Ans:- The finally keyword is used to create a block of
code that follows a try block. A finally block of code always executes, whether
or not an exception has occurred.
39.What things should be kept
in mind while creating your own exceptions in Java?
Ans:- While creating your own exception
−
All exceptions must be a child of Throwable.
If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.
You want to write a runtime exception,
you need to extend the RuntimeException class.
40.Define Inheritance?
Ans:- It is the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
41.When super keyword
is used?
Ans:- If the method
overrides one of its superclass's
methods, overridden method can be invoked through
the use of the keyword super. It can be
also used to refer to a hidden field.
42. What is Polymorphism?
Ans:- Polymorphism is the ability of an object to take on many forms. The most
common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
43.What is Abstraction?
Ans:- It refers to the ability to make a class abstract
in OOP. It helps to reduce the complexity and also improves the maintainability of the system.
44. What is Abstract
class?
Ans:- These classes cannot
be instantiated and are either partially implemented or not at all implemented. This class contains one or more abstract
methods which are simply method
declarations without a body.
45.When Abstract methods
are used?
Ans:- If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes,
you can declare the method in the parent class
as abstract.
46.What is Encapsulation?
Ans:- It is the technique of making the fields in a class private and providing access
to the fields via public methods. If a field is declared
private, it cannot
be accessed by anyone outside the class, thereby
hiding the fields within the class. Therefore encapsulation is also referred to
as data hiding.
47.What is the primary
benefit of Encapsulation?
Ans:- The main benefit of encapsulation is the ability to modify our
implemented code without
breaking the code of others who use our code. With this Encapsulation gives maintainability, flexibility and extensibility to our code.
48.What is an Interface?
Ans:- An interface is a collection of abstract methods.
A class implements an interface,
thereby inheriting the abstract methods
of the interface.
49.Give
some features of Interface?
Ans:- It includes −
Interface cannot be instantiated
![]()
An interface does not contain any constructors. All of the methods in an interface are abstract.
50.Define Packages in Java?
Ans:- A Package can be defined as a grouping
of related typesclasses, interfaces, enumerationsandannotations
providing access protection and name space management.
51.Why
Packages are used?
Ans:- Packages are used in Java in-order to prevent
naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces,
enumerations and annotations,
etc., easier.
52.What do you mean by Multithreaded program?
Ans:- A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread
defines a separate path of execution.
53.What are the two ways in which Thread can be created?
Ans:- Thread can be created by: implementing Runnable
interface, extending the Thread
54.class.
What is an applet?
Ans:- An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java application because
it has the entire Java API at its disposal.
55.An applet extend which class?
Ans:- An applet
extends java.applet.Applet class.
56.Explain garbage collection in Java?
Ans:- It uses garbage collection to free the memory. By cleaning those objects that is no longer reference by any of the program.
57.Define immutable object?
Ans:- An immutable object can’t be changed once it is created.
58.Explain the usage of this with constructors?
Ans:- It is used with variables or methods and used to call constructer of same class.
59. Explain Set Interface?
Ans:- It is a collection of element which cannot contain
duplicate elements. The Set interface contains only methods
inherited from Collection and adds the restriction that duplicate elements
are prohibited.
60.Explain TreeSet?
Ans:- It is a Set implemented when we want elements in a sorted order.
61.What
is Comparable Interface?
Ans:- It is used to sort collections and arrays of objects using the collections.sort and java.utils. The
objects of the class implementing the Comparable interface
can be ordered.
62.Difference between
throw and throws?
Ans:- It includes:
Throw
is used to trigger an exception where as throws
is used in declaration of exception.
Without
throws, Checked exception
cannot be handled
where as checked
exception can be propagated with throws
63.Explain the following line used under Java Program
−
Ans:- public static void main Stringargs[]
The following shows the explanation individually − public
− it is the access specifier.
![]()
static
− it allows main to be called
without instantiating a particular
instance of a class. void − it affirns the compiler that no value is returned by main.
![]()
main − this method is called
at the beginning of a Java program.
String args[ ] − args parameter is an instance
array of class String
64.Define JRE i.e. Java Runtime Environment?
Ans:- Java Runtime Environment is an implementation of the Java Virtual Machine
which executes Java programs. It provides the minimum requirements for executing a Java application;
65.What is JAR file?
Ans:- JAR files is Java Archive fles and it aggregates many files into one. It
holds Java classes in a library. JAR files are built on ZIP file format and have .jar file extension.
66.What is a WAR file?
Ans:- This is Web Archive File and used to store XML, java classes, and Java Server pages. which is used to distribute a collection of Java Server Pages, Java Servlets, Java classes, XML files, static Web pages etc.
67.Define JIT compiler?
Ans:- It improves the runtime performance of computer programs
based on bytecode.
68.What is the difference between object oriented programming
language and object based programming language?
Ans:- Object based programming languages follow all the features
of OOPs except Inheritance. JavaScript
is an example of object based programming languages.
69.What is the purpose of default constructor?
Ans:- The java compiler
creates a default
constructor only if there is no constructor in the class.
Can a constructor be made final?
No, this is not possible.
70.What
is static block?
Ans:- It is used to initialize the static data member,
It is executed before main method at the time of class loading.
71.Define composition?
Ans:- Holding the reference
of the other class within some other class is known as composition.
72. What
is function overloading?
Ans:- If a class has multiple
functions by same name but different parameters, it is known as Method Overloading.
73.What is function
overriding?
Ans:- If a subclass provides a specific implementation of a method that is already provided by its parent class,
it is known as Method
Overriding.
74.Difference between Overloading and Overriding?
Ans:- Method overloading increases
the readability of the program.
Method overriding provides
the specific implementation of the method that
is already provided by its super class parameter must be different
in case of overloading, parameter must be same in case of overriding.
75.What is final class?
Ans:- Final classes are created so the methods
implemented by that class cannot be overridden. It can’t be inherited.
76. What is Null Pointer Exception?
Ans:- A NullPointerException is thrown when calling the instance method of a null object,
accessing or modifying the field of a null object etc.
77.What are the ways in which a thread can enter the waiting state?
Ans:- A thread can enter the waiting state by invoking
its sleep method, by blocking on IO, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait method. It can also enter the waiting
state by invoking
its deprecated suspend
method.
78.How does multi-threading take place on a computer
with a single CPU?
Ans:- The operating system's
task scheduler allocates
execution time to multiple tasks. By quickly
switching between executing
tasks, it creates the impression that tasks execute sequentially.
79.What invokes a thread's run method?
Ans:- After a thread is started, via its start method of the Thread class, the
JVM invokes the thread's run method when the thread
is initially executed.
80.Does
it matter in what order catch statements
for FileNotFoundException and IOException are written?
Ans:- Yes, it does. The FileNoFoundException is inherited from the IOException. Exception's subclasses have to be caught first.
81.What is the difference
between yielding and sleeping?
Ans:- When a task invokes its yield method, it returns
to the ready state. When a task invokes its sleep method,
it returns to the waiting
state.
82.Why Vector
class is used?
Ans:- The Vector class provides the
capability to implement a growable array of objects. Vector proves to be very useful if you don't know the
size of the array in advance, or you just need one that can change
sizes over the lifetime of a program.
83.How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Ans:- Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character
set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns.
UTF-16
uses 16-bit and larger bit patterns.
84.What
are Wrapper classes?
Ans:- These are classes that allow primitive types to be accessed
as objects. Example: Integer,
Character, Double, Boolean
etc.
85.What is the difference between a Window and a Frame?
Ans:- The Frame class extends Window to define a main application window that can have a menu bar.
86.Which package has light weight
components?
Ans:- javax.Swing package.
All components in Swing, except JApplet,
JDialog, JFrame and JWindow are lightweight components.
87.What is the difference between the paint and repaint
methods?
Ans:- The paint method supports painting via a Graphics
object. The repaint
method is used to cause paint to be invoked
by the AWT painting thread.
88.What is
the purpose of File class?
Ans:- It is used
to create objects that provide
access to the files and directories of a local file system.
89.What is the difference between
the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
Ans:- The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.
90.Which class should you use to obtain design information about an object?
Ans:- The Class class is used to obtain information about an object's design and java.lang.Class class instance represent classes, interfaces in a running Java application.
91.What is the difference between static and non-static variables?
Ans:- A static variable is associated with the class as a whole rather than with specific instances
of a class. Non-static variables take on unique
values with each object instance.
92.What is Serialization and deserialization?
Ans:- Serialization is the
process of writing the state of an object to a byte stream. Deserialization is
the process of restoring these objects.
93.What are use cases?
Ans:- It is part of the analysis
of a program and describes
a situation that a program might encounter and what behavior
the program should
exhibit in that circumstance.
94.Explain the use of sublass in a Java program?
Ans:- Sub class inherits all the public and protected
methods and the implementation. It also inherits
all the default
modifier methods and their implementation.
95.How to add menushortcut to menu item?
Ans:- If there is a button instance called b1, you may add menu short cut by calling
b1.setMnemonic′F ′, so the user may be able to use Alt+F to click the button.
96.Can you write a Java class
that could be used both as
an applet as well as an application?
Ans:- Yes, just add a main method
to the applet.
97.What is the difference between Swing and AWT components?
Ans:- AWT components are heavy-weight,
whereas Swing components are lightweight. Heavy weight components depend on the local windowing
toolkit. For example,
java.awt.Button is a heavy weight
component, when it is running
on the Java platform for Unix platform, it maps to a real Motif button.
98.What's the difference between constructors and other methods?
Ans:- Constructors must have the same name as the class and can not return a value. They are only called once while regular
methods could be called many times.
99.Is there any limitation of using Inheritance?
Ans:- Yes, since inheritance inherits
everything from the super class and
interface, it may make
the subclass too clustering and sometimes error-prone when dynamic overriding or dynamic overloading in some situation.
100.When is the ArrayStoreException thrown?
Ans:- When copying elements between different
arrays, if the source or destination arguments
are not arrays or their types are not
compatible, an ArrayStoreException will be thrown.
101.Can
you call one constructor from another if a class has multiple
constructors?
Ans:- Yes, use this syntax.
102.What's the difference between the methods sleep and wait?
Ans:- The
code sleep2000;
puts thread aside for exactly two seconds. The code wait2000, causes a wait of up to two second. A thread could stop
waiting earlier if it receives the notify or notifyAll call. The method wait is defined in the class Object and the method sleep is defined in the class Thread.
103.When ArithmeticException is thrown?
Ans:- 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.
104.What is a transient variable?
Ans:- A transient
variable is a variable
that may not be serialized during Serialization and which is initialized by its default
value during de-serialization,
105.What is synchronization?
Ans:- Synchronization is the capability
to control the access of multiple threads
to shared resources. synchronized keyword in java provides
locking which ensures
mutual exclusive access of shared resource and prevent data race.
106.What is the Collections API?
Ans:- The Collections API is a set of classes and interfaces that support operations on collections of objects.
107.Does garbage collection guarantee that a program will not run out of memory?
Ans:- Garbage collection
does not guarantee
that a program will not run out of memory.
It is possible for programs to use up memory
resources faster than they are garbage
collected. It is also possible for programs to create
objects that are not subject
to garbage collection.
108.The immediate superclass of the Applet
class?
Ans:- Panel is the immediate
superclass. A panel provides space in which an application can attach any other component, including other panels.
109.Which Java operator is right associative?
Ans:- The = operator is right associative.
110.What is the difference
between a break statement and a continue
statement?
Ans:- A break statement results in the termination of the statement
to which it applies switch, for, do, or while. A continue statement is used to end the
current loop iteration and return control to the loop statement.
111.If a variable is declared as private, where may the variable be accessed?
Ans:- A private
variable may only be accessed
within the class in which it is
112.declared. What is the purpose of the System class?
Ans:- The purpose of the System class is to provide access to system
113.resources. List primitive Java types?
Ans:- The
eight primitive types are
byte, char, short, int, long, float, double,
and boolean.
1 1 4 . What is the relationship between
clipping and repainting under AWT?
Ans:- When a window is repainted by the AWT painting thread,
it sets the clipping regions to the area of the window
that requires repainting.
115.Which class is the immediate superclass of the Container class?
Ans:- Component class is the immediate super class.
116.What class of exceptions are generated by the Java run-time system?
Ans:- The Java runtime system
generates RuntimeException and Error exceptions.
117.Under what conditions is an object's finalize method invoked by the garbage collector?
Ans:- The garbage collector invokes an object's finalize method when it detects that the object has become unreachable.
118.How can a dead thread be restarted?
Ans:- A dead thread cannot be restarted.
119.Which arithmetic operations can result in the throwing
of an ArithmeticException?
Ans:- Integer / and % can result
in the throwing of an ArithmeticException.
120.Variable of the boolean type is automatically initialized as?
Ans:- The default
value of the boolean type is false.
121.Can try statements be nested?
Ans:- Yes
122.What are Class
Loaders?
Ans:- A class loader is an object that is responsible for loading classes.
The class Class Loader is an abstract class.
123.What is the difference between an Interface
and an Abstract class?
Ans:- An abstract
class can have instance methods
that implement a default behavior.
An Interface can only declare
constants and instance methods,
but cannot implement
default behavior and all methods
are implicitly abstract.
An interface has all public members and no implementation.
124.What will happen if static modifier
is removed from the signature
of the main method?
Ans:- Program throws
"No Such Method Error" error at runtime.
125.What is the default value of an object reference declared as an instance variable?
Ans:- Null,
unless it is defined explicitly.
126.Can a top level class be private or protected?
Ans:- No, a top level class can not be private or protected. It can have either "public" or no modifier.
127.Why do we need wrapper classes?
Ans:- We can pass them around as method parameters
where a method expects an object. It also provides utility methods.
128.What is the difference between error and an exception?
Ans:- An error is an irrecoverable condition
occurring at runtime.
Such as OutOfMemory error. Exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown
if the specified file does not exist.
129.Is it necessary that each try block
must be followed by a catch block?
Ans:- It is not necessary
that each try block must be followed by a catch block. It should be followed by either a catch block or a finally
block.
130.When a thread is created and started, what is its initial state?
Ans:- A
thread is in the ready state as initial state after it has been created and
started.
1 3 1 . What is the Locale class?
Ans:- The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural
region.
132.What are synchronized methods and synchronized statements?
Ans:- Synchronized methods
are methods that are used to control
access to an object. A synchronized statement can only be executed after a
thread has acquired the lock for the object or class referenced in the synchronized statement.
133.What is runtime polymorphism or dynamic method
dispatch?
Ans:- Runtime polymorphism or dynamic method dispatch is a process in which a
call to an overridden method is
resolved at runtime rather than at compile-time. In this process, an overridden
method is called through the reference variable
of a superclass.
134.What is Dynamic Binding late binding?
Ans:- Binding refers
to the linking of a procedure call to the code to be executed
in response to the call. Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.
135.Can constructor be inherited?
Ans:- No, constructor cannot be inherited.
136.What are the advantages of ArrayList over arrays?
Ans:- Array
List can grow dynamically and provides more powerful insertion and search mechanisms than arrays.
137.Why deletion in LinkedList is fast than ArrayList?
Ans:- Deletion in linked list is fast because it involves only updating the
next pointer in the node before the deleted
node and updating
the previous pointer
in the node after the deleted node.
138.How do you decide when to use ArrayList and LinkedList?
Ans:- If you need to frequently add and remove elements from the middle of the list and only access
the list elements sequentially, then LinkedList should be used. If you need to support random access, without
inserting or removing
elements from any place other than the end, then ArrayList should be used.
139.What is a Values Collection View ?
Ans:- It
is a collection returned by the values method of the Map Interface, It contains
all the objects present as values in the map.
140.What is dot operator?
Ans:- The dot operator. is used to access the instance variables
and methods of class objects.It is also used to access
classes and sub-packages from a package.
141.Where and how can you use a private constructor?
Ans:- Private constructor
is used if you do not want other classes to instantiate the object and to
prevent subclassing.T
142.What is type casting?
Ans:- Type casting means
treating a variable of one type as though
it is another type.
143. Describe life cycle of thread?
Ans:- A thread is a execution
in a program. The life cycle of a thread include −
![]()
![]()
![]()
![]()
Newborn state Runnable state
Running state Blocked
state Dead state
144.What is the difference between the >>
and >>> operators?
Ans:- The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted
out.
145.Which method of the Component class is used to set the position
and size of a component?
Ans:- Set Bounds method is used for this purpose.
146.What is the range of the short type?
Ans:- The range of the short type is
-215 to 2^15-1.
147. What is the immediate
superclass of Menu?
Ans:- MenuItem class
148.Does Java allow Default Arguments?
Ans:- No,
Java does not allow Default Arguments.
149.Which
number is denoted by leading zero in java?
Ans:- Octal Numbers are denoted by leading zero in java,
example: 06
150. Which number is denoted by leading 0x or 0X in java?
Ans:- Hexadecimal Numbers
are denoted by leading 0x or 0X in java, example − 0XF
151.Break statement can be used as labels in Java?
Ans:- Yes, an example can be break one;
152.Where import
statement is used in a Java program?
Ans:- Import statement is allowed at the beginning
of the program file after package statement.
153. Explain suspend method under
Thread class>
Ans:- It is used to pause or temporarily stop the execution
of the thread.
154.Explain is Alive method under Thread class?
Ans:- It is used to find out whether a thread is still running
or not.
155.What is current Thread?
Ans:- It
is a public static method used to obtain a reference to the current thread.
156.Explain main thread under Thread class execution?
Ans:- The main thread is created automatically and it begins to execute
immediately when a program starts.
It ia thread from which all other child threads
originate.
157.Life cycle of an applet includes which steps?
Ans:- Life cycle involves
the following steps
−
![]()
![]()
![]()
![]()
Initialization Starting Stopping
Destroying Painting
158.Why is the role of init method under applets?
Ans:- It initializes the applet and is the first method
to be called.
159.hich method is called by
Applet class to load an image?
Ans:- getImageURLobject, filename is used for this purpose.
160.Define code as an attribute of Applet?
Ans:- It
is used to specify the name of the applet class.
161.Define canvas?
Ans:- It is a simple drawing surface which are used for painting images or to perform other graphical operations.
162.Define Network Programming?
Ans:- It refers
to writing programs
that execute across multiple devices computers, in which the devices
are all connected
to each other
using a network.
163.What is a Socket?
Ans:- Sockets provide
the communication mechanism
between two computers
using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
164.Advantages of Java Sockets?
Ans:- Sockets
are flexible and sufficient. Efficient socket based programming can be easily implemented for general communications. It cause low network traffic.
165.Disadvantages
of Java Sockets?
Ans:- Socket based communications allows only to send packets of raw data between
applications. Both the client-side and server-side have to provide mechanisms to make the data useful in any way.
166.Which class is used by server applications to obtain a port and listen for client requests?
Ans:- java.net.ServerSocket class is used by server applications
to obtain a port and listen for client requests
167.Which class represents the socket that both the client and server use to communicate with each other?
Ans:- java.net.Socket class represents the socket that both the client and server use to communicate with each other.
168.Why Generics are used in Java?
Ans:- Generics provide
compile-time type safety that allows
programmers to catch invalid types at compile time.
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods
or, with a single class declaration, a set of related types.
169.What environment variables do I need to set on my machine in order to be able to run Java programs?
Ans:- CLASSPATH and PATH are the two variables.
170.Is there any need to import java.lang
package?
Ans:- No, there is no need
to import this package. It is by default loaded internally by the JVM.
171. What is Nested top-level
class?
Ans:- If
a class is declared within a class and specify the static modifier, the
compiler treats the class just like any other top-level
class. Nested top-level class is an Inner class.
172.What is Externalizable interface?
Ans:- Externalizable is an interface
which contains two methods readExternal and writeExternal. These
methods give you a
control over the serialization mechanism.
173.If System.exit 0; is written at the end of the try block, will the finally
block still execute?
Ans:- No in this case the finally block will not execute because when you say System.exit 0; the control immediately goes out of the
program, and thus finally never executes.
174.What is daemon
thread?
Ans:- Daemon thread is a low priority
thread, which runs intermittently in the back ground doing the garbage
collection operation for the java runtime system.
175.Which method is used to create the daemon thread? Ans:- setDaemon method is used to create a daemon
thread.
176.hich method must be implemented by all threads?
Ans:- All tasks must
implement the run method .
177.hat
is the GregorianCalendar class?
Ans:- The GregorianCalendar provides support for traditional
Western calendars
178.What is the SimpleTimeZone class?
Ans:- The SimpleTimeZone class provides support
for a Gregorian calendar.
179.What is the difference between the size and capacity
of a Vector?
Ans:- The size is the number of elements actually
stored in the vector, while capacity is the maximum
number of elements
it can store at a given instance
of time.
180.Can a vector contain heterogenous objects?
Ans:- Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.
181.What is an enumeration?
Ans:- An enumeration is an interface
containing methods for accessing the underlying data structure from which the enumeration is obtained. It allows sequential access to all the elements
stored in the collection.
182.What is difference between Path and Classpath?
Ans:- Path and Classpath are operating system level environment variales. Path is defines where the system can find the
executables. exe files
and classpath is used to specify the location of .class files.
183.Can
a class declared as private be accessed outside it's package?
Ans:- No, it's not possible
to accessed outside it's package.
184.What are the restriction imposed on a static method or a static block of code?
Ans:- A static method should not refer to instance
variables without creating
an instance and cannot use "this" operator
to refer the instance.
185.Can an Interface
extend another Interface?
Ans:- Yes an Interface can inherit another
Interface, for that matter an Interface can extend more than one Interface.
186.Which object oriented Concept
is achieved by using overloading and overriding?
Ans:- Polymorphism
187.What is an object's lock and which object's have locks?
Ans:- An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired
the object's lock.
188.What is Downcasting?
Ans:- casting
down the hierarchy.
189. What are order of precedence and associativity and how are they used?
Ans:- Order of precedence determines the order in which operators
are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left.
190.If a method is declared
as protected, where may the method be accessed?
Ans:- A protected method may only be accessed
by classes or interfaces of the same package or by subclasses of the class in which
it is declared.
191.What is the difference
between inner class and nested class?
Ans:- If the access modifier of the inner class is static, then it becomes
nested class.
192.What restrictions are placed on method overriding?
Ans:- Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method
it overrides.
193.What
is constructor chaining and how is it achieved in Java?
Ans:- A child object constructor always first needs to construct its parent. In Java it is done via an implicit call to the no-args constructor as the first statement.
194.Can
a double value be cast to a byte?
Ans:- Yes, a double value can be cast to a byte.
Most Popular Java Programming Interview Questions.
Q #1) Write a Java Program to reverse a string
without using String inbuilt function.
Answer: Here, we are initializing a string variable str and
making use of the string builder class.
The object of the string builder class str2 will be
further used to append the value stored in the string variable str.
Thereafter, we are using the inbuilt function of the string builder (reverse())
and storing the new reversed string in str2. Finally, we are printing
str2.
Following program code explains this:
|
public class FinalReverseWithoutUsingStringMethods
{ public static void main(String[]
args) { // TODO Auto-generated method stub String
str = "Automation"; StringBuilder
str2 = new StringBuilder(); str2.append(str); str2
= str2.reverse(); // used
string builder to reverse System.out.println(str2); } } |
Output:
noitamotuA
Q #2) Write a Java Program to reverse a string
without using String inbuilt function reverse().
Answer: There are several ways with which you can reverse
your string if you are allowed to use the other string inbuilt functions.
Method 1:
In this method, we are initializing a string
variable called str with the value of your given string. Then, we are
converting that string into a character array with the toCharArray() function.
Thereafter, we are using for loop to iterate between each character in reverse
order and printing each character.
|
public class FinalReverseWithoutUsingInbuiltFunction
{ public static void main(String[]
args) { String
str = "Saket Saurav"; char chars[] =
str.toCharArray(); // converted
to character array and printed in reverse order for(int i= chars.length-1; i>=0; i--) { System.out.print(chars[i]); } } } |
Output:
varuaS tekaS
Method 2:
This is another method in which you are declaring
your string variable str and then using Scanner class to declare an object with
a predefined standard input object.
This program will accept the string value through
the command line (when executed).
We have used nextLine() which will read the input
with the spaces between the words of a string. Thereafter, we have used a
split() method to split the string into its substrings(no delimiter given
here). Finally, we have printed the string in reverse order using for loop.
|
import java.util.Scanner; public class ReverseSplit
{ public static void main(String[]
args) { // TODO Auto-generated method stub String
str; Scanner
in = new Scanner(System.in); System.out.println("Enter your String"); str
= in.nextLine(); String[]
token = str.split(""); //used split method to print in reverse order for(int i=token.length-1; i>=0; i--) { System.out.print(token[i]
+ ""); } } } |
Output:
Enter your String
Softwaretestinghelp
plehgnitseterawtfoS
Method 3:
This is almost like method 2, but here we did not
use the split() method. We have used the scanner class and nextLine() for
reading the input string. Then, we have declared an integer length which has
the length of the input string.
Thereafter, we have printed the string in the
reverse order using for loop. However, we have used the charAt(index) method
which will return the character at any specific index. After each iteration,
the character will be concatenated to reverse the string variable.
Finally, we have printed the reverse string
variable.
|
import java.util.Scanner; public class Reverse { public static void main(String[]
args) { // TODO Auto-generated method stub String
original, reverse = ""; System.out.println("Enter the string to be reversed"); Scanner
in = new Scanner(System.in); original
= in.nextLine(); int length =
original.length(); for(int i=length-1; i>=0; i--) { reverse
= reverse + original.charAt(i); //used inbuilt method charAt() to reverse the
string } System.out.println(reverse); } } |
Output:
Enter the string to be reversed
automation testing
gnitset noitamotua
Q #3) Write a Java Program to swap two numbers
using the third variable.
Answer: In this example, we have made use of the Scanner
class to declare an object with a predefined standard input object. This
program will accept the values of x and y through the command line (when
executed).
We have used nextInt() which will input the value
of an integer variable ‘x’ and ‘y’ from the user. A temp variable is also
declared.
Now, the logic of the program goes like this – we
are assigning temp or third variable with the value of x, and then assigning x
with the value of y and again assigning y with the value of temp. So, after the
first complete iteration, the temp will have a value of x, x will have a value
of y and y will have a value of temp (which is x).
|
import java.util.Scanner; public class SwapTwoNumbers
{ public static void main(String[]
args) { // TODO Auto-generated method stub int x, y, temp; System.out.println("Enter x and y"); Scanner
in = new Scanner(System.in); x
= in.nextInt(); y
= in.nextInt(); System.out.println("Before Swapping" + x + y); temp
= x; x
= y; y
= temp; System.out.println("After Swapping" + x + y); } } |
Output:
Enter x and y
45
98
Before Swapping4598
After Swapping9845
Q #4) Write a Java Program to swap two numbers
without using the third variable.
Answer: Rest all things will be the same as the above
program. Only the logic will change. Here, we are assigning x with the value x
+ y which means x will have a sum of both x and y.
Then, we are assigning y with the value x – y which
means we are subtracting the value of y from the sum of (x + y). Till here, x
still has the sum of both x and y. But y has the value of x.
Finally, in the third step, we are assigning x with
the value x – y which means we are subtracting y (which has the value of x)
from the total (x + y). This will assign x with the value of y and vice versa.
|
import java.util.Scanner; class SwapTwoNumberWithoutThirdVariable { public static void main(String
args[]) { int x, y; System.out.println("Enter x and y"); Scanner
in = new Scanner(System.in); x
= in.nextInt(); y
= in.nextInt(); System.out.println("Before Swapping\nx = "+x+"\ny =
"+y); x
= x + y; y
= x - y; x
= x - y; System.out.println("After Swapping without third variable\nx =
"+x+"\ny =
"+y); } } |
Output:
Enter x and y
45
98
Before Swapping
x = 45
y = 98
After Swapping without a third variable
x = 98
y = 45
Q #5) Write a Java Program to count the number
of words in a string using HashMap.
Answer: This is a collection class program where we
have used HashMap for storing the string.
First of all, we have declared our string variable
called str. Then we have used split() function delimited by single space so
that we can split multiple words in a string.
Thereafter, we have declared HashMap and iterated
using for loop. Inside for loop, we have an if-else statement in which wherever
at a particular position, the map contains a key, we set the counter at that
position and add the object to the map.
Each time, the counter is incremented by 1. Else,
the counter is set to 1.
Finally, we are printing the HashMap.
Note: The same program can be used to count the number of characters in
a string. All you need to do is to remove one space (remove space delimited in
split method) in String[] split = str.split(“”);
|
import java.util.HashMap; public class FinalCountWords
{ public static void main(String[]
args) { // TODO Auto-generated method stub String
str = "This this is is done by Saket Saket"; String[]
split = str.split(" "); HashMap<String,Integer>
map = new HashMap<String,Integer>(); for (int i=0;
i<split.length; i++) { if (map.containsKey(split[i]))
{ int count =
map.get(split[i]); map.put(split[i],
count+1); } else { map.put(split[i],
1); } } System.out.println(map); } } |
Output:
{Saket=2, by=1, this=1, This=1, is=2, done=1}
Q #6) Write a Java Program to iterate HashMap
using While and advance for loop.
Answer: Here we have inserted three elements in HashMap
using put() function.
The size of the map can get using the size()
method. Thereafter, we have used a While loop for iterating through the map
which contains one key-value pair for each element. Keys and Values can be
retrieved through getKey() and getValue().
Likewise, we have used advanced for loop where we
have a “me2” object for the HashMap.
|
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIteration
{ public static void main(String[]
args) { // TODO Auto-generated method stub HashMap<Integer,String>
map = new HashMap<Integer,String>(); map.put(2, "Saket"); map.put(25, "Saurav"); map.put(12, "HashMap"); System.out.println(map.size()); System.out.println("While Loop:"); Iterator
itr = map.entrySet().iterator(); while(itr.hasNext())
{ Map.Entry
me = (Map.Entry) itr.next(); System.out.println("Key is " + me.getKey() + " Value is " + me.getValue()); } System.out.println("For Loop:"); for(Map.Entry
me2: map.entrySet()) { System.out.println("Key is: " + me2.getKey() + " Value is: " + me2.getValue()); } } } |
Output:
3
While Loop:
Key is 2 Value is Saket
Key is 25 Value is Saurav
Key is 12 Value is HashMap
For Loop:
Key is: 2 Value is: Saket
Key is: 25 Value is: Saurav
Key is: 12 Value is: HashMap
Q #7) Write a Java Program to find whether a
number is prime or not.
Answer: Here, we have declared two integers temp and num
and used Scanner class with nextInt(as we have integer only).
One boolean variable isPrime is set to true.
Thereafter, we have used for loop starting from 2, less than half of the number
is entered and incremented by 1 for each iteration. Temp will have the remainder
for every iteration. If the remainder is 0, then isPrime will be set to False.
Based on isPrime value, we are coming to the
conclusion that whether our number is prime or not.
|
import java.util.Scanner; public class Prime { public static void main(String[]
args) { // TODO Auto-generated method stub int temp, num; boolean isPrime = true; Scanner
in = new Scanner(System.in); num
= in.nextInt(); in.close(); for (int i = 2; i<=
num/2; i++) { temp
= num%i; if (temp == 0) { isPrime
= false; break; } } if(isPrime) System.out.println(num
+ "number is prime"); else System.out.println(num
+ "number is not a prime"); } } |
Output:
445
445number is not a prime
Q #8) Write a Java Program to find whether a
string or number is palindrome or not.
Answer: You can use any of the reverse string program
explained above to check whether the number or string is palindrome or not.
What you need to do is to include one if-else
statement. If the original string is equal to a reversed string then the number
is a palindrome, otherwise not.
|
import java.util.Scanner; public class Palindrome { public static void main
(String[] args) { String
original, reverse = ""; Scanner
in = new Scanner(System.in); int length; System.out.println("Enter the number or String"); original
= in.nextLine(); length
= original.length(); for (int i =length -1; i>;=0; i--) { reverse
= reverse + original.charAt(i); } System.out.println("reverse is:" +reverse); if(original.equals(reverse))
System.out.println("The number is palindrome"); else System.out.println("The number is not a palindrome"); } } |
Output:
For String-
Enter the number or String
vijay
reverse is:yajiv
The number is not a palindrome
For Number-
Enter the number or String
99
reverse is:99
The number is palindrome
Q #9) Write a Java Program for the Fibonacci
series.
Answer: Fibonacci series is a series of numbers where after
the initial two numbers, every occurring number is the sum of two preceding
numbers.
For Example 0,1,1,2,3,5,8,13,21………
In this program, we have used Scanner class again
with nextInt (discussed above). Initially, we are entering (through command
line) the number of times the Fibonacci has to iterate. We have declared
integer num and initialized a,b with zero and c with one. Then, we have used
for loop to iterate.
The logic goes like a is set with the value of b
which is 0, then b is set with the value of c which is 1. Then, c is set with
the sum of both a and b.
|
import java.util.Scanner; public class Fibonacci { public static void main(String[]
args) { int num, a = 0,b=0, c =1; Scanner
in = new Scanner(System.in); System.out.println("Enter the number of times"); num
= in.nextInt(); System.out.println("Fibonacci Series of the number is:"); for (int i=0; i<num;
i++) { a
= b; b
= c; c
= a+b; System.out.println(a
+ "");
//if you want to print on
the same line, use print() }
} } |
Output:
Enter the number of times
10
Fibonacci Series of the number is:
0
1
1
2
3
5
8
13
21
34
Q #10) Write a Java Program to iterate
ArrayList using for-loop, while-loop, and advance for-loop.
Answer: In this program, we have inserted three
elements and printed the size of the ArrayList.
Then, we have used While Loop with an iterator.
Whenever the iterator has (next) element, it will display that element until we
reach the end of the list. So it will iterate three times.
Likewise, we have done for Advanced For Loop where
we have created an object called obj for the ArrayList called list. Then printed
the object.
Thereafter, we have put the condition of For Loop
where the iterator i is set to 0 index, then it is incremented by 1 until the
ArrayList limit or size is reached. Finally, we have printed each element using
a get(index) method for each iteration of For Loop.
|
import java.util.*; public class arrayList { public static void main(String[]
args) { ArrayList
list = new ArrayList(); list.add("20"); list.add("30"); list.add("40"); System.out.println(list.size()); System.out.println("While Loop:"); Iterator
itr = list.iterator(); while(itr.hasNext())
{ System.out.println(itr.next()); } System.out.println("Advanced For Loop:"); for(Object obj :
list) { System.out.println(obj); } System.out.println("For Loop:"); for(int i=0;
i<list.size(); i++) { System.out.println(list.get(i)); } } } |
Output:
3
While Loop:
20
30
40
Advanced For Loop:
20
30
40
For Loop:
20
30
40
Q #11) Write a Java Program to demonstrate an
explicit wait condition check.
Answer: There are two main types of wait – implicit and
explicit. (We are not considering Fluent wait in this program)
The implicit wait is those waits that are executed
irrespective of any condition. In the below program, you can see that it is for
Google Chrome and we have used some inbuilt methods to set the property,
maximizing window, URL navigation, and web element locating.
|
WebDriverWait wait = new WebDriverWait(driver,
20); WebElement element2 =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Software testing - Wikipedia"))); element2.click(); |
In the above piece of code, you can see that we
have created an object wait for WebDriverWait and then we have searched for
WebElement called element2.
The condition is set in such a way that the
webdriver will have to wait until we see the link “Software testing –
Wikipedia” on a web page. It won’t execute if it does not find this link. If it
does, then it will do a mouse click on that link.
package Codes;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class explicitWaitConditionCheck {
public static void main(String[]
args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\webdriver\\chromedriver.exe");
ChromeOptions
options = new ChromeOptions();
options.addArguments("--disable-arguments");
WebDriver
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20,
TimeUnit.SECONDS);
driver.navigate().to("https://www.google.com");
WebElement
element = driver.findElement(By.name("q"));
element.sendKeys("Testing");
element.submit();
WebDriverWait
wait = new WebDriverWait(driver,
20);
WebElement
element2 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Software testing - Wikipedia")));
element2.click();
}}
|
|
Q #12) Write a Java Program to demonstrate
Scroll up/ Scroll down.
Answer: All the lines of codes are easily relatable
as we have discussed in our previous example.
However, in this program, we have included our
JavascriptExecutor js which will do the scrolling. If you see the last line of
the code, we have passed window.scrollBy(arg1,arg2).
If you want to scroll up then pass some value in
arg1 if you want to scroll down then pass some value in arg2.
|
package Codes; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class ScrollDown { public static void main(String[]
args) { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C:\\webdriver\\chromedriver.exe"); WebDriver
driver = new ChromeDriver(); JavascriptExecutor
js = (JavascriptExecutor) driver; driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20,
TimeUnit.SECONDS); driver.get("https://www.google.com"); WebElement
element = driver.findElement(By.name("q")); element.sendKeys("SoftwareTestingHelp"); element.sendKeys(Keys.ENTER); js.executeScript("window.scrollBy(0,1000)"); } } |
Q #13) Write a Java Program to open all links
of gmail.com.
Answer: It is a typical example of advanced for loop
which we have seen in our previous programs.
Once you have opened a website such as Gmail using
get() or navigate().to(), you can use a tagName locator to find the tag name of
a website that will return all the tags.
We have advanced for loop where we have created a
new WebElement link2 for a link(which already has located all the tags), then
we have got all the links through getAttribute(“href”) and got all the texts
through getText().
|
package Codes; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class openAllLinks
{ public static void main(String[]
args) { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.drive", "C:\\webdriver\\chromedriver.exe"); WebDriver
driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20,
TimeUnit.SECONDS); driver.manage().window().maximize(); driver.get("https://www.gmail.com/"); java.util.List<WebElement>
link = driver.findElements(By.tagName("a")); System.out.println(link.size()); for (WebElement
link2: link) { //print the links i.e. http://google.com or
https://www.gmail.com System.out.println(link2.getAttribute("href")); //print the links text System.out.println(link2.getText()); } } } |
Output:
Starting Chrome Driver 2.38.551601
(edb21f07fc70e9027c746edd3201443e011a61ed) on port 16163
Only local connections are allowed.
4
https://support.google.com/chrome/answer/6130773?hl=en-GB
Learn more
https://support.google.com/accounts?hl=en-GB
Help
https://accounts.google.com/TOS?loc=IN&hl=en-GB&privacy=true
Privacy
https://accounts.google.com/TOS?loc=IN&hl=en-GB
Terms
Q #14) Write a Selenium code to switch to the
previous tab.
Answer: We have demonstrated the use of the Robot
class. We see this as an important third party because we can achieve the
different navigation within a browser and its tabs if you know the shortcut
keys.
For example, if you have three tabs open in your chrome and
you want to go to the middle tab, then you have to press control + 2 from your
keyboard. The same thing can be achieved through the code as well.
Observe the following code (just after we see the
instantiation of Robot class). we have used the Robot class object called a
robot with two inbuilt methods keyPress(KeyEvenet.VK_*) and keyRelease(KeyEvenet.VK_*).
|
package Codes; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class PreviousTab { public static void main(String[]
args) throws AWTException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C:\\webdriver\\chromedriver.exe"); WebDriver
driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(20,
TimeUnit.SECONDS); driver.get("https://www.google.com"); WebElement
element1 = driver.findElement(By.name("q")); element1.sendKeys("software testing help"); element1.sendKeys(Keys.ENTER); String
a = Keys.chord(Keys.CONTROL,Keys.RETURN); driver.findElement(By.partialLinkText("Software Testing Help - A Must Visit Software
Testing Portal")).sendKeys(a); Robot
robot = new Robot(); //
instantiated robot class robot.keyPress(KeyEvent.VK_CONTROL);
// with robot class you
can easily achieve anything if you know the shortcut keys robot.keyPress(KeyEvent.VK_2);
// here, we have just
pressed ctrl+2 robot.keyRelease(KeyEvent.VK_CONTROL);
// once we press and
release ctrl+2, it will go to the second tab. robot.keyRelease(KeyEvent.VK_2);
//if you again want to go
back to first tab press and release vk_1 } } |
Q #15) Write a Java Program to find the
duplicate characters in a string.
Answer: In this program, we have created a string variable
str and initialized an integer count with zero.
Then, we have created a character array to convert
our string variable to the character. With the help of for loop, we are
performing a comparison between different characters at different indexes.
If two characters of consecutive index match, then
it will print that character and the counter will be incremented by 1 after
each iteration.
|
public class DuplicateCharacters
{ public static void main(String[]
args) { // TODO Auto-generated method stub String
str = new String("Sakkett"); int count = 0; char[] chars =
str.toCharArray(); System.out.println("Duplicate characters are:"); for (int i=0; i<str.length();i++)
{ for(int j=i+1;
j<str.length();j++) { if (chars[i] ==
chars[j]) { System.out.println(chars[j]); count++; break; } } } } } |
Output:
Duplicate characters are:
k
t
Q #16) Write a Java Program to find the
second-highest number in an array.
Answer: In this program, we have initialized an array
with 10 random elements out of which we are going to find the second-highest
number. Here, we have two integers- the largest and second-largest. Both set to
the first index of the element. Then, we have printed all the elements using
for loop.
Now, the logic is when the element at the 0th index
is greater than the largest, then assign arr[0] to largest and secondLargest to
largest. Again, if the element at the 0th index is greater than the
secondLargest, then assign secondLargest to arr[0].
This will be repeated for each iteration and
ultimately after comparing or completing iterations up to array length will
give you the secondLargest element.
|
package codes; public class SecondHighestNumberInArray
{ public static void main(String[] args) { int arr[] = { 100,14, 46, 47, 94, 94, 52, 86, 36, 94, 89 }; int largest = 0; int secondLargest
= 0; System.out.println("The given array is:"); for (int i = 0; i <
arr.length; i++) { System.out.print(arr[i]
+ "\t"); } for (int i = 0; i <
arr.length; i++) { if (arr[i] >
largest) { secondLargest
= largest; largest
= arr[i]; } else if (arr[i] > secondLargest) { secondLargest
= arr[i]; } } System.out.println("\nSecond largest number is:" + secondLargest); System.out.println("Largest Number is: " +largest); } } |
Output:
The given array is:
100 14 46 47 94 94 52 86 36 94 89
Second largest number is:94
Largest Number is: 100
Q #17) Write a Java Program to check Armstrong
number.
Answer: First of all we need to understand what
Armstrong Number is. Armstrong number is the number which is the sum of the
cubes of all its unit, tens and hundred digits for three-digit numbers.
153 = 1*1*1 + 5*5*5 + 3*3*3 = 1 + 125 + 27 = 153
If you have a four-digit number lets say
1634 = 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1 +
1296 + 81 + 256 = 1634
Now, in this program, we have a temp and integers
declared. We have initialized c with value 0. Then, we need to assign the
integer value which we are going to check for Armstrong (in our case, let us
say 153). Then we have assigned our temp variable with that number which we are
going to check.
Thereafter, we have used while conditional check
where the remainder is assigned to a and the number is divided by 10 and
assigned to n. Now, our c variable which was set to zero initially is assigned
with c+(a*a*a). Suppose we have to evaluate a four-digit number then c should
be assigned with c + (a*a*a*a).
Lastly, we have put an if-else statement for
conditional checking where we have compared the value contained in c against
temp(which has the actual number stored at this point). If it matches, then the
number is Armstrong otherwise not.
|
class Armstrong{ public static void main(String[]
args) { int c=0,a,temp;
int n=153;//It is the number to check Armstrong temp=n;
while(n>0) {
a=n%10; n=n/10; c=c+(a*a*a);
}
if(temp==c)
System.out.println("armstrong number"); else System.out.println("Not armstrong number"); }
} |
Output:
armstrong number
Q #18) Write a Java Program to remove all
white spaces from a string with using replace().
Answer: This is a simple program where we have our
string variable str1.
Another string variable str2 is initialized with
the replaceAll option which is an inbuilt method to remove n number of
whitespaces. Ultimately, we have printed str2 which has no whitespaces.
|
class RemoveWhiteSpaces { public static void main(String[]
args) { String
str1 = "Saket
Saurav is a
QualityAna list"; //1. Using replaceAll() Method String
str2 = str1.replaceAll("\\s", ""); System.out.println(str2); } } } |
Output:
SaketSauravisaQualityAnalist
Q #19) Write a Java Program to remove all
white spaces from a string without using replace().
Answer: This is another approach to removing all the white
spaces. Again, we have one string variable str1 with some value. Then, we have
converted that string into a character array using toCharArray().
Then, we have one StringBuffer object sb which will
be used to append the value stored at chars[i] index after we have included for
loop and one if condition.
If the condition is set such that then the element
at i index of the character array should not be equal to space or tab. Finally,
we have printed our StringBuffer object sb.
|
class RemoveWhiteSpaces { public static void main(String[]
args) { String
str1 = "Saket
Saurav is an Autom ation Engi
ne er"; char[] chars =
str1.toCharArray(); StringBuffer
sb = new StringBuffer(); for (int i = 0; i <
chars.length; i++) { if( (chars[i]
!= ' ')
&& (chars[i] != '\t') ) { sb.append(chars[i]); } }
System.out.println(sb);
//Output : CoreJavajspservletsjdbcstrutshibernatespring } } |
Output:
SaketSauravisanAutomationEngineer
Q #20) Write a Java Program to read an excel.
Answer: These types of programs are generally used in
Selenium framework. We have added detailed comments for every step to make the
program more understandable.
The logic starts after we have loaded the sheet in
which the data is stored. We are trying to import email and password. For this,
we are retrieving the cell using getRow() and getCell() method. Let’s say we
have email and passwords at the 1st and 2nd cell.
Then we are setting the type of cell to string.
Thereafter we are carrying out a normal web element locator operation (By.id)
where we have passed unique locator values such as “email” and “password” which
will identify these elements.
Finally, we are sending keys using element.sendKeys
where cell.getStringCellValue() is the key. This will return you the value
stored at cell number 1 and 2 respectively.
|
@Test public void ReadData() throws IOException { // Import excel sheet from a webdriver directory
which is inside c drive. //DataSource is the name of the excel File
src=new File("C:\\webdriver\\DataSource.xls"); //This step is for loading the file. We have used
FileInputStream as //we are reading the excel. In case you want to
write into the file, //you need to use FileOutputStream. The path of
the file is passed as an argument to FileInputStream FileInputStream
finput = new FileInputStream(src); //This step is to load the workbook of the excel
which is done by global HSSFWorkbook in which we have //passed finput as an argument. workbook
= new HSSFWorkbook(finput); //This step is to load the sheet in which data is
stored. sheet=
workbook.getSheetAt(0); for(int i=1;
i<=sheet.getLastRowNum(); i++) { // Import data for Email. cell
= sheet.getRow(i).getCell(1); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id("email")).sendKeys(cell.getStringCellValue()); // Import data for the password. cell
= sheet.getRow(i).getCell(2); cell.setCellType(Cell.CELL_TYPE_STRING); driver.findElement(By.id("password")).sendKeys(cell.getStringCellValue()); } } |
Java Program to Display Even Numbers From 1 to 100
In this section, we will create a Java program to display even numbers from 1 to 100. To learn
the Java even number program, you must have the
basic knowledge of Java
for
loop and if statement.
We can use different ways to display even numbers:
- Using Java for Loop
- Using nested-if Statement
- Using while Loop
Using Java for Loop
In the following example, we have declared a variable named
number and initialized it with 100 (the limit to print the even number). We
have used a for loop
that executes up to 100 times and for each
iteration of i the if statement checks the number is even or not. After
printing each even number, the value if i is increased by 1.
In order to check the number, we have divided the number by 2 if
it does not leave any remainder, the number is even and the print statement
prints that numberNext
Stay
DisplayEvenNumbersExample1.java
1.
public class DisplayEvenNumbersExample1
- {
3.
public static void main(String args[])
- {
5.
int number=100;
- System.out.print("List of even numbers from 1 to "+number+": ");
7.
for (int i=1; i<=number; i++)
- {
9.
//logic to check if the number is even or not
- //if i%2 is equal to zero, the number is even
11.
if (i%2==0)
- {
13.
System.out.print(i + " ");
- }
15.
}
- }
17.
}
Output:
List of even numbers from 1 to 100: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Using nested-if Statement
The following program is slightly different from the above
program because we have defined a method that contains the logic to check even
number. Inside the method, we have used nested-if statement.
DisplayEvenNumbersExample2.java
1.
public class DisplayEvennumbersExample2
- {
3.
public static void main(String[] args)
- {
5.
System.out.println("List of even numbers: ");
- //method calling
7.
displayEvenNumbers(1, 100);
- }
9.
//method that checks the number is even or not
- private static void displayEvenNumbers(int number, int end)
11.
{
- if(number>end)
13.
return;
- if(number%2==0)
15.
{
- //prints the even numbers
17.
System.out.print(number +" ");
- //calling the method and increments the number by 2 if the number is even
19.
displayEvenNumbers(number + 2, end);
- }
21.
else
- {
23.
//increments the number by 1 if the number is odd
- displayEvenNumbers(number + 1, end);
25.
}
- }
27.
}
Output:
List of even numbers: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100
Using while Loop
In the following program, we have replaced the for loop
with while loop.
DisplayEvenNumbersExample3.java
1.
import java.util.Scanner;
- public class DisplayEvenNumbersExample3
3.
{
- public static void main(String[] args)
5.
{
- int number, i;
7.
Scanner sc=new Scanner(System.in);
- System.out.print("Enter the limit: ");
9.
number = sc.nextInt();
- i=2;
11.
System.out.print("Lit of even numbers: ");
- //the while loop executes until the condition become false
13.
while(i<=number)
- {
15.
//prints the even number
- System.out.print(i +" ");
17.
//increments the variable i by 2
- i=i+2;
19.
}
- }
21.
}
Output:
Enter the limit: 100Lit of even numbers: 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42
Java Program to Display Odd Numbers From 1 to 100
In this section, we will create a Java program to display odd numbers from 1 to 100. To learn
the Java odd number program, you must have the
basic knowledge of Java
for
loop and if statement.
We can use different Java loops to display odd numbers:
- Using Java for Loop
- Using nested-if Statement
- Using while Loop
Using Java for Loop
In the following example, we have declared a variable named
number and initialized it with 100 (the limit to print the odd number). We have
used a for loop
that executes up to 100 times and for each iteration
of i the if statement checks the number is odd or not. After printing each odd
number, the value if i is increased by 1.
In order to check the number, we have divided the number by 2 if
it leaves a remainder, the number is odd and the print statement prints that
number.
DisplayOddNumbersExample1.java
1.
public class DisplayOddNumbersExample1
- {
3.
public static void main(String args[])
- {
5.
int number=100;
- System.out.print("List of odd numbers from 1 to "+number+": ");
7.
for (int i=1; i<=number; i++)
- {
9.
//logic to check if the number is odd or not
- //if i%2 is not equal to zero, the number is odd
11.
if (i%2!=0)
- {
13.
System.out.print(i + " ");
- }
15.
}
- }
17.
}
Output:
List of odd numbers from 1 to 100: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
Using nested-if Statement
The following program is slight different from the above program
because we have defined a method that contains the logic to check odd number.
Inside the method, we have used nested-if statement.
DisplayOddNumbersExample2.java
1.
public class DisplayOddnumbersExample2
- {
3.
public static void main(String[] args)
- {
5.
System.out.println("List of odd numbers: ");
- //method calling
7.
displayOddNumbers(1, 100);
- }
9.
//method that checks the number is odd or not
- private static void displayOddNumbers(int number, int end)
11.
{
- if(number>end)
13.
return;
- if(number%2!=0)
15.
{
- //prints the odd numbers
17.
System.out.print(number +" ");
- //calling the method and increments the number by 2 if the number is odd
19.
displayOddNumbers(number + 2, end);
- }
21.
else
- {
23.
//increments the number by 1 if the number is odd
- displayOddNumbers(number + 1, end);
25.
}
- }
27.
}
Output:
List of odd numbers: 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99
Using while Loop
In the following program, we have replaced the for loop
with while loop
.
DisplayOddNumbersExample3.java
1.
import java.util.Scanner;
- public class DisplayOddNumbersExample3
3.
{
- public static void main(String[] args)
5.
{
- int number, i;
7.
Scanner sc=new Scanner(System.in);
- System.out.print("Enter the limit: ");
9.
number = sc.nextInt();
- i=1;
11.
System.out.print("Lit of odd numbers: ");
- //the while loop executes until the cond\ition become false
13.
while(i<=number)
- {
15.
//prints the odd number
- System.out.print(i +" ");
17.
//increments the variable i by 2
- i=i+2;
19.
}
- }
21.
}
Output:
Enter the limit: 100Lit of odd numbers: 1 3 5 7 9 11 15 17 13 19 21 23 25 27 29 31 33 35 37 39 41