0% found this document useful (0 votes)
17 views

Java Notes

Java is an object-oriented programming language that can be used to create platforms. It allows for creating modular and reusable code and is cross-platform, meaning programs can run on many systems. It provides keywords, variables, data types, operators, control flow statements and methods to develop applications.

Uploaded by

Md shamimsorkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

Java Notes

Java is an object-oriented programming language that can be used to create platforms. It allows for creating modular and reusable code and is cross-platform, meaning programs can run on many systems. It provides keywords, variables, data types, operators, control flow statements and methods to develop applications.

Uploaded by

Md shamimsorkar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Java 1st Class

What is Java?

 Programming Language
 object-oriented programming language
 a Platform

Platform:

 hardware or software environment in which a program runs, is known as a platform. Since Java has
a runtime environment (JRE) and API, it is called a platform.

Why use Java?

 Java is fast
 Secure - With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
 reliable
 Java is object-oriented - allows us to create modular programs and reusable code.
 Java is platform-independent (Cross-Platform) - Java is its ability to move easily from one
computer system to another. The ability to run the same program on many different systems is
crucial to World Wide Web software
 Supported help community is vast

Difference between JDK, JRE, and JVM?

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other languages and compiled to Java
bytecode

The JVM performs the following main tasks:


Loads code
Verifies code
Executes code
Provides runtime environment

JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications.
It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It
contains a set of libraries + other files that JVM uses at runtime.

JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment
which is used to develop Java applications and applets. It physically exists. It contains JRE + development
tools.

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java),
a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to complete the
development of a Java Application.

What is Variable in java?


A variable is a container for storing data value while the Java program is executed.
A variable is assigned with a data type. Variable is a name of memory location.
Each variable in Java has a specific type, which determines the size and layout of the variable's memory;
the range of values that can be stored within that memory;
and the set of operations that can be applied to the variable.

How many kinds of variable in java?

There are three types of variables in Java:

Local variable
Instance variable
Static/Class variable

What is data type ?

Data types specify the different sizes and values that can be stored in the variable

There are two data types available in Java.

Primitive Data Types


Non-primitive/Reference/Object Data Types

What is primitive data type and how number is that?


Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

There are eight primitive data types supported by Java. Primitive data types are predefined by the language
and named by a keyword.
byte, short, int, long, float, double, boolean and char

What is keyword in java?

Java keywords are also known as reserved words.


Java reserved keywords are predefined words, which are reserved for any functionality or meaning. These
keywords are used by the syntax of Java for some functionality. If we use a reserved word as our variable
name, object name or class name., it will throw an error. In Java, every reserved word has a unique
meaning and functionality.

abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else,
enum, extends, final, finally, float, for,goto, if, implements, import. Instanceof, int, interface, long, native,
new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this
throw, throws, transient, try, void, volatile, while

What is Identifier and write rules of identifier?

Java Identifiers
Identifiers in Java are symbolic names used for identification.
They can be a class name, variable name, method name, package name, constant name, and interface. In
Java, There are some reserved words that can not be used as an identifier.

For every identifier there are some conventions that should be used before declaring them.

Rules for Java identifier

There are some rules and conventions for declaring the identifiers in Java.
If the identifiers are not properly declared, we may get a compile-time error. Following are some rules and
conventions for declaring identifiers:

A valid identifier must have characters [A-Z] or [a-z] or numbers [0-9], and underscore(_) or a dollar sign
($). for example, @fdfd is not a valid identifier because it contains a special character which is @.There
should not be any space in an identifier. e.g., hello world is an invalid identifier.An identifier should not
contain a number at the starting. For example, 123HelloWorld is an invalid identifier.An identifier should
be of length 4-15 letters only. However, there is no limit on its length. But, it is good to follow the standard
conventions. We can't use the Java reserved keywords as an identifier such as int, float, double, char, etc.
For example, int double is an invalid identifier in Java.6. An identifier should not be any query language
keywords such as SELECT, FROM, COUNT, DELETE, etc.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
What is operator in java?

 Operators are used to perform operations on variables and values.


 Operator in Java is a symbol that is used to perform operations.

What is comment in java and describe it?

used to make the program or java code more readable, understandable by adding the details of the code
- makes easy to maintain the code and to find the errors easily
- can be used to provide information or explanation about the variable, method, class, or any statement

 comments the line is ignored by Java (will not be executed).

Three types of comments in Java

Single Line Comment


Multi Line Comment
Documentation Comment

What is Misc Operators (Conditional Operator) ?

Conditional operator is also known as the ternary operator.


This operator consists of three operands and is used to evaluate Boolean expressions.

The goal of the operator is to decide, which value should be assigned to the variable.

variable = Expression1 ? Expression2: Expression3

The operator is written as −


variable x = (expression) ? value if true : value if false

What is java arithmetic operator?

ava arithmetic operators are used to perform addition, subtraction, multiplication, and division.
Arithmetic operators are used to perform common mathematical operations.

Write down some operator name?


Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators

What is control flow statement?

Java compiler executes the code from top to bottom. The statements in the code are executed according to
the order in which they appear. However, Java provides statements that can be used to control the flow of
Java code. Such statements are called control flow statements. It is one of the fundamental features of Java,
which provides a smooth flow of program.

Describe types of control flow statements?

Types of Java Control Statements

Java provides three types of control flow statements.

Decision Making statements

 if statements
 switch statement

Loop statements

 for loop
 Enhanced for loop
 while loop
 do while loop
 for-each loop

Jump statements

 break statement
 continue statement
How many types of if statements in java?

Simple if statement
if-else statement
if-else-if ladder
Nested if-statement

What is loops in java?

The Java for loop is used to iterate a part of the program several times.
If the number of iteration is fixed, it is recommended to use for loop.

A for loop is useful when we know how many times a task is to be repeated.

There are three types of for loops in Java.

Simple for Loop


For-each or Enhanced for Loop
Labeled for Loop

What is java for-each-loop and describe this?

It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse
the array or collection elements.

The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more
readable. It is known as the for-each loop because it traverses each element one by one.

The drawback of the enhanced for loop is that it cannot traverse the elements in reverse order. Here, you do
not have the option to skip any element because it does not work on an index basis. Moreover, you cannot
traverse the odd or even elements only.

But, it is recommended to use the Java for-each loop for traversing the elements of array and collection
because it makes the code readable.

Advantages
It makes the code more readable.
It eliminates the possibility of programming errors.

Describe while loop in java?

The Java while loop is used to iterate a part of the program repeatedly until the specified Boolean condition
is true. As soon as the Boolean condition becomes false, the loop automatically stops.

The while loop is considered as a repeating if statement.


If the number of iteration is not fixed, it is recommended to use the while loop.
What is method in java?

In general, a method is a way to perform some task.

A method is a block of code that performs a specific task.

Similarly, the method in Java is a collection of instructions that performs a specific task.

A Method is a block of code which only runs when it is called.

It provides the reusability of code. We can also easily modify code using methods.

A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. We write a method once and use it many times. We do not require to write code
again and again.

It also provides the easy modification and readability of code, just by adding or removing a chunk of code.
The method is executed only when we call or invoke it.

The most important method in Java is the main() method.

Describe Method Declaration in java?

The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments. It has six components that are known as method header.

Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.

Access Specifier or Modifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier.

Public, protected, private, default

Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc.

If the method does not return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to
the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.

How can we named a method?

While defining a method, remember that the method name must be a verb and start with a lowercase letter.
If the method name has more than two words, the first name must be a verb followed by adjective or noun.
In the multi-word method name, the first letter of each word must be in uppercase except the first word.

For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

It is also possible that a method has the same name as another method name in the same class, it is known
as method overloading.

How many types of method in java and describe this?


There are two types of methods in Java:
1. Predefined Method
2. User-defined Method

Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method.

We can directly use these methods just by calling them in the program at any point. Some predefined
methods are length(), equals(), compareTo(), sqrt(), etc.

When we call any of the predefined methods in our program, a series of codes related to the corresponding
method runs in the background that is already stored in the library.

Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.

User-defined Method

The method written by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.

What is Static Method?

A method that has static keyword is known as static method. In other words, a method that belongs to a
class rather than an instance of a class is known as a static method. We can also create a static method by
using the keyword static before the method name.

The main advantage of a static method is that we can call it without creating an object. It can access static
data members and also change the value of it. It is used to create an instance method. It is invoked by using
the class name. The best example of a static method is the main() method.

What is oop in java?

OOP stands for Object-Oriented Programming.


Object-Oriented Programming is a methodology or paradigm to design a program using classes and
objects.
Everything in Java is associated with classes and objects, along with its attributes and methods
main aim of object-oriented programming is to implement real-world entities, for example, object, classes,
abstraction, inheritance, polymorphism, etc.

It simplifies software development and maintenance by providing some concepts:


Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
The popular object-oriented languages are java, C#, PHP, Python, C++ etc.

Write some advantages of OOP?


Object-oriented programming has several advantages:
1) OOPs makes development and maintenance easier
2) OOPs provides data hiding
3) OOPs provides the ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language
4. OOP is faster and easier to execute
5. OOP provides a clear structure for the programs
6. OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to maintain,
modify and debug
7. OOP makes it possible to create full reusable applications with less code and shorter development time

What is class in java?

A class is a group of objects which have common properties.

It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

Fields
Methods
Constructors
Blocks
Nested class and interface

Describe object and its properties?

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It
can be physical or logical (tangible and intangible). The example of an intangible object is the banking
system.

Entity is a group of states associated together in a single unit.

An object has three characteristics:


State/Attributes/Field: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to
the external user. However, it is used internally by the JVM to identify each object uniquely.

Object Definitions:

The object is an entity which has state and behavior.


The object is an instance of a class.
An object is a real-world entity.

There are three steps when creating an object from a class −

Declaration − A variable declaration with a variable name with an object type.


Instantiation − The 'new' keyword is used to create the object.
Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new object

How can we initialize object in java?

There are 3 ways to initialize object in Java.


By reference variable
By method
By constructor

Describe java static keyword and variable?

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an
instance of the class.
The static can be:Variable (also known as a class variable)Method (also known as a class
method)BlockNested class

Java static variable

 Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
 There would only be one copy of each class variable per class, regardless of how many objects are
created from it.
 Static variables are rarely used other than being declared as constants. Constants are variables that
are declared as public/private, final, and static. Constant variables never change from their initial
value.
 Static variables are stored in the static memory. It is rare to use static variables other than declared
final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program stops.
 Visibility is similar to instance variables. However, most static variables are declared public since
they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it
is false; and for object references, it is null. Values can be assigned during the declaration or
within the constructor. Additionally, values can be assigned in special static initializer blocks.
 Static variables can be accessed by calling with the class name ClassName.VariableName.
 The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memor

What is constructor in java?


Constructor is a special kind of method
Constructor name should be same as class name
Constructor will not return any value
Constructor will be invoked at the time of object creation.
Constructor will take parameter just like a method
Constructor is used for initialize the values
In Java, a constructor is a block of codes similar to the method.

The constructor is called when an object of a class is created.

It is a special type of method which is used to initialize the state of the object.
At the time of calling constructor, memory for the object is allocated in the memory.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.

When is a Constructor called?

 Each time an object is created using a new() keyword, at least one constructor (it could be the
default constructor) is invoked to assign initial values to the data members of the same class.
 It can be used to set initial values for object attributes
Describe Rules for creating Java constructor?

 Constructor name must be the same as its class name


 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
 Constructors are called only once at the time of Object creation
 Access modifiers can be used in constructor declaration to control its access i.e which other class
can call the constructor.

How many Types of Java constructors?

There are two types of constructors in Java:

 Default constructor (no-arg constructor)


 Parameterized constructor

What is default constructor in Java ?

A constructor is called "Default Constructor" when it doesn't have any parameter.

Note: If there is no constructor in a class, compiler automatically creates a default constructor.

What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending on
the type.

What is Java Parameterized Constructor?

A constructor which has a specific number of parameters is called a parameterized constructor.

Constructors can also take parameters, which is used to initialize attributes.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. we can provide the
same values also.

Difference between constructor and method in Java:

There are many differences between constructors and methods. They are given below.
Java Constructor vs Java Method:
A constructor is used to initialize the state of an object.
A method is used to expose the behavior of an object.
A constructor must not have a return type.
A method must have a return type.
The constructor is invoked implicitly.
The method is invoked explicitly.
The Java compiler provides a default constructor if you don't have any constructor in a class.
The method is not provided by the compiler in any case.
The constructor name must be same as the class name.
The method name may or may not be same as the class name.

Write Rules for creating Java constructor?

 Constructor name must be the same as its class name


 A Constructor must have no explicit return type
 A Java constructor cannot be abstract, static, final, and synchronized
 Constructors are called only once at the time of Object creation
 Access modifiers can be used in constructor declaration to control its access i.e which other class
can call the constructor.

What is Java – Inheritance?

Inheritance can be defined as the process where

 acquiring methods and variables from parent class to child class that is called Inheritance
 mechanism in java by which one class is allowed to inherit the features(fields and methods) of
another class
 Inherit attributes and methods from one class to another class
 one object acquires all the properties and behaviors of a parent object

The class which inherits the properties of other is known as subclass (derived class, child class) and the
class whose properties are inherited is known as superclass (base class, parent class). When we inherit from
an existing class, we can reuse methods and fields of the parent class. Moreover, we can add new methods
and fields in our current class also. Inheritance represents the IS-A relationship which is also known as a
parent-child relationship. With the use of inheritance the information is made manageable in a hierarchical
order. Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why And When To Use Inheritance?

 For Method Overriding


 For Code Reusability
 reuse attributes and methods of an existing class when we create a new class
How to use inheritance in Java?

by extends keywords

What is Access Modifiers in Java?

There are two types of modifiers in Java: access modifiers and non-access modifiers.
Access Modifiers - controls the access level

Non-Access Modifiers - do not control access level, but provides other functionality
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class.
We can change the access level of fields, constructors, methods, and class by applying the access modifier
on it.
There are four types of Java access modifiers:
Private, Protected, Public, Default
Private: The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.

private String format;

Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default. No keyword required.
Protected: The access level of a protected modifier is within the package and outside the package through
child class. If you do not make the child class, it cannot be accessed from outside the package.
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.
The protected access modifier cannot be applied to class and interfaces.

our intention is to expose this method to its subclass only, that’s why we have used protected modifier.

Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

A class, method, constructor, interface, etc. declared public can be accessed from any other class.
Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging
to the Java Universe.

Access Control and Inheritance:


The following rules for inherited methods are enforced −

 Methods declared public in a superclass also must be public in all subclasses.


 Methods declared protected in a superclass must either be protected or public in subclasses; they
cannot be private.
 Methods declared private are not inherited at all, so there is no rule for them.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.
What is Encapsulation in java?

Encapsulation in Java

 Encapsulation in Java is a mechanism to wrap up variables(data) and methods(code) together as a


single unit.
 The meaning of Encapsulation is to make sure that "sensitive" data is hidden from users.
 The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private it means it can only be accessed within the same class. No outside class can
access private data member (variable) of other class.

Example: a capsule which is mixed of several medicines.

What is Getter and Setter in Java?

Getter and Setter in Java are two conventional methods used to retrieve and update values of a variable.

 The setter method is used for updating values


 the getter method is used for reading or retrieving the values. They are also known as an accessor
and mutator.

private variables can only be accessed within the same class (an outside class has no access to it).
However, it is possible to access them if we provide public get and set methods.
The get method returns the variable value, and the set method sets the value.

Write some Advantage of Encapsulation in Java?

 Provide Data hiding


 Code reusability
 Code is possible to modify without breaking the code
 It improves maintainability - hiding implementation details reduce complexity
 By providing only a setter or getter method, we can make the class read-only or write-only.
 It provides us the total control over the data what is is stored in its fields.
 It is a way to achieve data hiding in Java because other class will not be able to access the data
through the private data members.

What is Sub Class/Child Class/derived class?


Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child
class
What is Super Class/Parent Class/base class?

Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent
class.

Describe types of inheritance in java?

On the basis of class, there can be three types of inheritance in java:


single
multilevel
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.

What is single inheritance in java?

When a class inherits another class, it is known as a single inheritance

What is Multilevel Inheritance ?

When there is a chain of inheritance, it is known as multilevel inheritance.

What is Hierarchical Inheritance?

When two or more classes inherits a single class, it is known as hierarchical inheritance.

What is Multiple Inheritance ?

When one class inherits multiple classes, it is known as multiple inheritance.

Multiple inheritance is not supported in Java through class.

In java, we can achieve multiple inheritances only through Interfaces.

interface InterfaceName extends InterfaceOne, InterefaceTwo

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider
a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes
have the same method and you call it from child class object, there will be ambiguity to call the method of
A or B class.

What is Polymorphism in Java?


Polymorphism in Java is a concept by which we can perform a . Polymorphism is derived from 2 Greek
words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We
can perform polymorphism in java by method overloading and method overriding.

What is Method Overloading?

If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

There are two ways to overload the method in java

By changing number of arguments


By changing the data type

What is Java – Overriding?

 If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
 If a subclass provides the specific implementation of the method that has been declared by one of
its parent class, it is known as method overriding.
 Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding method.

Usage of Java Method Overriding

Method overriding is used to provide the specific implementation of a method which is already provided
by its superclass.
Method overriding is used for runtime polymorphism

Rules of java method Overriding?

 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
 Final methods can not be overridden
 Static methods can not be overridden
 Private methods can not be overridden
 Invoking overridden method from sub-class : We can call parent class method in overriding
method using super keyword.he overriding method must have same return type
 We can not override main method. because the main is a static method
What is Super keyword in Method Overriding?

The super keyword is used for calling the parent class method/constructor. super.myMethod() calls the
myMethod() method of base class while super() calls the constructor of base class.

Advantage of Overriding method in java?

The main advantage of method overriding is that the class can give its own specific implementation to a
inherited method without even modifying the parent class code.

This is helpful when a class has several child classes, so if a child class needs to use the parent class
method, it can use it and the other classes that want to have different implementation can use overriding
feature to make changes without touching the parent class code.

What is difference between method overloading and method overriding in java?

 Method overloading is used to increase the readability of the program.

Method overriding is used to provide the specific implementation of the method that is already provided by
its super class.

 Method overloading is performed within class.

Method overriding occurs in two classes that have IS-A (inheritance) relationship.

 In case of method overloading, parameter must be different.

In case of method overriding, parameter must be same.

Java class # 6

What is Sub Class/Child Class/derived class?

Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child
class.
What is Super Class/Parent Class/base class?

Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent
class.

What is Code Reusability?

As the name specifies, reusability is a mechanism which facilitates us to reuse the fields and methods of
the existing class when we create a new class. We can use the same fields and methods already defined in
the previous class.

What Is java Java Abstraction?

 In Object-oriented programming, abstraction is a process of hiding the implementation details from


the user, only the functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it does it.
 process of hiding certain details and showing only essential information to the user.
 it shows only essential things to the user and hides the internal details.

Example: sending SMS where you type the text and send the message. You don't know the internal
processing about the message delivery.

In Java, abstraction is achieved using Abstract classes and interfaces.


The abstract keyword is a non-access modifier, used for classes and methods:

What is abstract class and describe its properties?

A class which is declared with the abstract keyword is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
The abstract keyword is a non-access modifier, used for classes and methods.
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited
from another class).

Points to Remember:

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the method.
What is abstract method in java ?

Abstract Method in Java

 A method which is declared as abstract and does not have implementation is known as an abstract
method.
 can only be used in an abstract class, and it does not have a body. The body is provided by the
subclass (inherited from).

Why And When To Use Abstract Classes and Methods?

 To achieve security
 hide certain details and only show the important details of an object.

Describe the Advantages of Abstraction?

 It reduces the complexity of viewing the things.


 Avoids code duplication and increases reusability.
 Helps to increase the security of an application or program as only important details are provided
to the user.

What is Encapsulation vs Data Abstraction?

Encapsulation vs Data Abstraction:


Encapsulation is data hiding(information hiding) while Abstraction is detailed hiding(implementation
hiding).
While encapsulation groups together data and methods that act upon the data, data abstraction deal with
exposing the interface to the user and hiding the details of implementation.

An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.

Some rule’s:

 An abstract class is a class that is declared with abstract keyword.


 An abstract method is a method that is declared without an implementation.
 An abstract class may or may not have all abstract methods. Some of them can be concrete
methods
 A method defined abstract must always be redefined in the subclass,thus making overriding
compulsory OR either make subclass itself abstract.
 Any class that contains one or more abstract methods must also be declared with abstract keyword.
 There can be no object of an abstract class.That is, an abstract class can not be directly instantiated
with the new operator.
 An abstract class can have parametrized constructors and default constructor is always present in
an abstract class.

When to use abstract classes and abstract methods?

There are situations in which we will want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method. That is,
sometimes we will want to create a superclass that only defines a generalization form that will be
shared by all of its subclasses, leaving it to each subclass to fill in the details.

What is Java – Interfaces?

An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class.

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction.


There can be only abstract methods in the Java interface, not method body.
It is used to achieve abstraction and multiple inheritance in Java.
Interfaces specify what a class must do and not how.
the methods declared in an interface are by default abstract (only method signature, no body).
In other words, you can say that interfaces can have abstract methods and variables. It cannot have
a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.

Note: The Java compiler adds public and abstract keywords before the interface method. Moreover,
it adds public, static and final keywords before data members.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

 It is used to achieve abstraction.


 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
 Interfaces are used to implement abstraction.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.

Describe Multiple inheritance in Java by interface?

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as


multiple inheritance.

MultipleinheritanceinJavabyinterface.png

Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class
because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class.

What is Java array?

Normally, an array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The elements of an
array are stored in a contiguous memory location. It is a data structure where we store similar elements. We
can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored
on 1st index and so on.

What is advantage and disadvantage java array?

Advantages

 Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
 Random access: We can get any data located at an index position.

Disadvantages

 Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.

What is datastructure in java?

Data Structure is a way to store and organize data so that it can be used efficiently.

Data Structure includes all topics of Data Structure such as Array, Pointer, Structure, Linked List, Stack,
Queue, Graph, Searching, Sorting, Programs, etc.

The data structure name indicates itself that organizing the data in memory. There are many ways of
organizing the data in the memory i.e., array in C language.
Array is a collection of memory elements in which data is stored sequentially, i.e., one after another. In
other words, we can say that array stores the elements in a continuous manner. This organization of data is
done with the help of an array of data structures.
The data structure is not any programming language like C, C++, java, etc. It is a set of algorithms that we
can use in any programming language to structure the data in the memory

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is Java Collection Framework?

The Collection in Java is a framework that provides an architecture to store and manipulate the group of
objects.

Selenium Class # 1
What is Automation Testing?

Usage of automation tools for executing test cases is known as Automation Testing.
It is a type of testing for which we need resources with the knowledge of scripting, etc.

Automation Testing is a software testing technique that performs using special automated testing software
tools to execute a test case suite. On the contrary, Manual Testing is performed by a human sitting in front
of a computer carefully executing the test steps.

Why Automation?

Manual Testing has some limitations. Many times we have to do repetitive testing and doing things
repetitively can be boring. Testing with valid and invalid inputs can make you irate. To err is human and
when it comes to quality we just can’t compromise.
Time constraint is the most important thing when we talk about the release of the software. If development
teams fail to complete the development process before the deadline, then the company loses customers and
no one can afford this.
For Example, it could be time-consuming to test software with negative inputs.
Cost is the major constraint for any software development process. Maintenance costs can be a major issue
for undetected defects. Automation comes into the picture to conquer all the above issues.
Enlisted below are a few pointers that justify the reason for using Automation Testing:

 It helps us to deliver a product with good quality.


 It saves time.
 It is beneficial to test the multilingual site.
 It allows us to test the software in multiple browsers.
 It does not require human intervention.
 It increases the speed of automation.
 It helps us to increase Test Coverage
 It helps you to generate the report for Test Execution, you just can’t modify it and hence it is
useful for team lead/managers.
 By using an Automation tool we can record and replay test cases. For Example, if someone from
your team is on leave or you want to access a record of test cases executed by the previous
employees then this option is beneficial. Selenium IDE is the tool that allows us to record the test
cases.

When to use and when not use Automation?

Scenarios Where We Can Consider Automation Testing

 We can consider stable parts of the application for Automation.


 Areas where we have to do frequent testing. For example, if you have to test some areas after each
build.
 Test cases with the possibility of human making mistakes should be considered for Automation.
 Test cases that need to be tested with a different set of data or a large amount of data should be
automated.
 If there is any functionality that is having a high-risk condition, then it needs to be automated.
 Test cases that are unable to perform manually, For Example, Multilingual sites.
 Test cases that need to be tested with different browsers and different environments should be
considered for Automation.

Where We Should Not Think Of Automation?

 Areas of application which change frequently should not be considered for Automation.
 Test cases that are executed on an ad-hoc basis should not be considered for Automation.
 A newly designed test and the one that is not executed manually should never be considered for
Automation.

Write down Testing Types which can not be considered for Automation?

 Exploratory Testing: This is the type of testing where we need skilled tester as the requirement
specification document is not much descriptive. The tester needs to use his skills and knowledge to
test the test cases.
 Usability Testing: While testing for usability, the tester needs to think like an end-user and check
for the user-friendly nature of the application. Indeed a tool can’t think like a human being.
 Ad-hoc Testing: As the word, Ad-hoc itself tells that it is unplanned, a tester plays an important
role.

Which Test Cases to Automate?


Test cases to be automated can be selected using the following criterion to increase the automation ROI

 High Risk – Business Critical test cases


 Test cases that are repeatedly executed
 Test Cases that are very tedious or difficult to perform manually
 Test Cases which are time-consuming

Write down Benefits of Automation Testing?

Following are the Test Automation benefits:

 70% faster than the manual testing


 Wider test coverage of application features
 Reliable in results
 Ensure Consistency
 Saves Time and Cost
 Improves accuracy
 Human Intervention is not required while execution
 Increases Efficiency
 Better speed in executing tests
 Re-usable test scripts
 Test Frequently and thoroughly
 More cycle of execution can be achieved through automation
 Early time to market

What is Selenium?

Selenium is one of the most widely used open source Web UI (User Interface) automation testing suite.
Selenium is a suite of tools for automating web browsers.
Selenium is an open-source tool that is used for test automation.
Selenium is a popular open-source web-based automation tool.
Selenium is a free (open-source) automated testing framework used to validate web applications across
different browsers and platforms.
It has capabilities to operate across different browsers and operating systems.
Selenium is not just a single tool but a set of tools that helps testers to automate web-based applications
more efficiently.

Selenium supports automation across different browsers, platforms and programming languages.
Selenium can be easily deployed on platforms such as Windows, Linux, Solaris and Macintosh. Moreover,
it supports OS (Operating System) for mobile applications like iOS, windows mobile and android.
Selenium supports a variety of programming languages through the use of drivers specific to each
language.Languages supported by Selenium include C#, Java, Perl, PHP, Python and Ruby.
We can use these multiple programming languages like Java, C#, Python etc to create Selenium Test
Scripts. Testing done using the Selenium testing tool is usually referred to as Selenium Testing.
Currently, Selenium Web driver is most popular with Java and C#. Selenium test scripts can be coded in
any of the supported programming languages and can be run directly in most modern web
browsers. Browsers supported by Selenium include Internet Explorer, Mozilla Firefox, Google Chrome and
Safari.

Selenium can be used to automate functional tests and can be integrated with automation test tools such as
Maven, Jenkins, & Docker to achieve continuous testing. It can also be integrated with tools such as
TestNG, & JUnit for managing test cases and generating reports.

Describe Selenium Features?

 Selenium is an open source and portable Web testing Framework.


 Selenium IDE provides a playback and record feature for authoring tests without the need to learn
a test scripting language.
 It can be considered as the leading cloud-based testing platform which helps testers to record their
actions and export them as a reusable script with a simple-to-understand and easy-to-use interface.
 Selenium supports various operating systems, browsers and programming languages. Following is
the list: Programming Languages: C#, Java, Python, PHP, Ruby, Perl, and JavaScript
 Operating Systems: Android, iOS, Windows, Linux, Mac, Solaris.
 Browsers: Google Chrome, Mozilla Firefox, Internet Explorer, Edge, Opera, Safari, etc.
 It also supports parallel test execution which reduces time and increases the efficiency of tests.
 Selenium can be integrated with frameworks like Ant and Maven, Gradlefor source code
compilation.
 Selenium can also be integrated with testing frameworks like TestNG for application testing and
generating reports.
 Selenium requires fewer resources as compared to other automation test tools.
 WebDriver API has been indulged in selenium which is one of the most important modifications
done to selenium.

Describe Selenium Limitations?

 Selenium does not support automation testing for desktop applications.


 Selenium requires high skill sets in order to automate tests more effectively.
 Since Selenium is open source software, we have to rely on community forums to get our technical
issues resolved.
 We can't perform automation tests on web services like SOAP or REST using Selenium.
 We should know at least one of the supported programming languages to create tests scripts in
Selenium WebDriver.
 It does not have built-in Object Repository like UTF/QTP to maintain objects/elements in
centralized location. However, we can overcome this limitation using Page Object Model.
 Selenium does not have any inbuilt reporting capability; you have to rely on plug-ins like JUnit
and TestNG for test reports.
 It is not possible to perform testing on images. We need to integrate Selenium with Sikuli for
image based testing.
 Creating test environment in Selenium takes more time as compared to vendor tools like UFT,
RFT Silk

 No one is responsible for new features usage; they may or may not work properly.
 Selenium does not provide any test tool integration for Test Management.

Write down Selenium components?

Selenium is not just a single tool but a suite of software, each with a different approach to support
automation testing.

It comprises of four major components which include:

 Selenium Integrated Development Environment (IDE)


 Selenium Remote Control (Now Deprecated)
 Selenium WebDriver
 Selenium Grid

1.Selenium Integrated Development Environment (IDE)


Selenium IDE is implemented as Firefox extension which provides record and playback functionality on
test scripts. It allows testers to export recorded scripts in many languages like HTML, Java, Ruby, RSpec,
Python, C#, JUnit and TestNG. You can use these exported script in Selenium RC or Webdriver.

Note: Selenium IDE has limited scope and the generated test scripts are not very robust and portable.
2. Selenium Remote Control
Selenium RC (officially deprecated by selenium)allows testers to write automated web application UI test
in any of the supported programming languages. It also involves an HTTP proxy server which enables the
browser to believe that the web application being tested comes from the domain provided by proxy server.

3. Selenium WebDriver
Selenium WebDriver is the successor to Selenium RC which sends commands directly to the browser and
retrieves results. It is the most important component of Selenium Suite.
Selenium WebDriver provides a programming interface to create and execute test cases. Test scripts are
written in order to identify web elements on web pages and then desired actions are performed on those
elements.
Selenium WebDriver performs much faster as compared to Selenium RC because it makes direct calls to
the web browsers. RC on the other hand needs an RC server to interact with the web browser.
Since, WebDriver directly calls the methods of different browsers hence we have separate driver for each
browser.

Write down Some of the most widely used web drivers?

Mozilla Firefox Driver (Gecko Driver)


Google Chrome Driver
Internet Explorer Driver
Opera Driver
Safari Driver
HTML Unit Driver (a special headless driver)

Describe Selenium 3 Architecture?

The architecture for Selenium 3 includes the JSON Wire Protocol. However, Selenium 4 does not include
the JSON Wire Protocol, and that’s the contrast between Selenium 3 and Selenium 4. JSON stands for
JavaScript Object Notation.
The JSON Wire Protocol has an assignment to transfer information from the client to the server over
HTTP. HTTP is an acronym for Hyper Text Transfer Protocol. A Selenium request is sent from the
Selenium Client and WebDriver Language Bindings component. Next, the request is received by JSON
Wire Protocol Over HTTP, then secured by the Browser Driver.
Afterwards, the request command is delivered to a Web Browser where the automation takes place. When
the automation is complete, a response travels back to the Browser Driver, JSON Wire Protocol, and
Selenium Client & WebDriver Language Bindings.

Describe Selenium 4 Architecture?

The biggest difference between Selenium 3 and Selenium 4 involves W3C WebDriver Protocol, which is
the main reason for Selenium’s upgrade. W3C is acronym for World Wide Web Consortium, which is an
international community that develops web standards. The WebDriver Protocol is responsible for
controlling a web browser’s behavior.

Unlike Selenium 3, Selenium 4 has direct communication between the client and server. The client still has
2 parts (Selenium Client & WebDriver Language Bindings) while Browser Drivers are the server.

Selenium Client sends out a request to perform a command.


The WebDriver Language Bindings is a code library designed to drive actions.

Browser Drivers receive the request and then return a response after an automation Test Script executes on
the Web Browser.

The Selenium Client & WebDriver Language Bindings is a part of the architecture where each language
has their own unique bindings. Bindings mean that the same commands written for one language are also
written for another language. For example, Java has a set of commands that have also been written for
other languages (C#, Python JavaScript, and Ruby). When it comes to the Browser Drivers and Web
Browsers, WebDriver drives each browser using the browser’s built-in automation support. A Browser
Driver such as ChromeDriver controls the Chrome browser.

Write selenium 4 advantages?


With the upgrade, Selenium 4 successively gained at least 3 advantages. The advantages are:

 Standards
 Stability
 Updated Actions API

The standards are an advantage because our Test Scripts run more consistently on each browser. All
browser vendors have a standard. Since Selenium 4 is compliant with W3C WebDriver, there is no more
required encoding and decoding of the request.

Stability is another advantage because of backwards compatibility. The Java Bindings and the Selenium
Server provide a mechanism to use the old JSON Wire Protocol. There have been updates to the Actions
API for keyboard and mouse events. It supports a way to carry out more than one action at the same time,
like pressing 2 keys.

What is Selenium WebDriver?

WebDriver is a tool for automating testing web applications.


Selenium WebDriver is the most important component of Selenium Tools' Suite.
WebDriver interacts directly with the browser without any intermediar.
Selenium WebDriver- Architecture
Selenium WebDriver API provides communication facility between languages and browsers.
architectural representation of Selenium WebDriver.
architectural representation of Selenium WebDriver.

Describe Selenium WebDriver- Features?

Some of the most important features of Selenium WebDriver are:


Multiple Browser Support: Selenium WebDriver supports a diverse range of web browsers such as Firefox,
Chrome, Internet Explorer, Opera and many more. It also supports some of the non-conventional or rare
browsers like HTMLUnit.

Multiple Languages Support: Java, C#, JavaScript,


PHP, Ruby, Pearl and Python
Speed: WebDriver performs faster as compared to other tools of Selenium Suite. Unlike RC, it doesn't
require any intermediate server to communicate with the browser; rather the tool directly communicates
with the browser.

Describe selenium basic components?

There are four basic components of WebDriver Architecture:

 Selenium Language Bindings


 JSON Wire Protocol
 Browser Drivers
 Real Browsers

Selenium Language Bindings / Selenium Client Libraries:

Selenium developers have built language bindings/Selenium Client Libraries in order to support multiple
languages. For instance, if you want to use the browser driver in java, use the java bindings. All the
supported language bindings can be downloaded from the official website
(https://www.seleniumhq.org/download/#client-drivers ) of Selenium.

JSON Wire Protocol:


JSON (JavaScript Object Notation) is an open standard for exchanging data on web. It supports data
structures like object and array. So, it is easy to write and read data from JSON.
It provides a transport mechanism to transfer data between a server and a client.

What is Web Element?

The term web element refers to a HTML element. The HTML documents are composed of HTML
elements. It consists a start tag, an end tag and the content in between. For instance, a HTML element is
written as: "<tagname> content </tagname>"
Input = tagname name=attribute, txtUsername=value
<input name="txtUsername" id="txtUsername" type="text">

Write Some WebElement Commands?

1 driver.get("URL")- To navigate to an application.


2. element.sendKeys("inputtext") - Enter some text into an input box.
3. element.clear() - Clear the contents from the input box.
4. driver.close() - Closes the current browser associated with the driver.

What is Locators in selenium?

Locators in selenium Webdriver

 A locator is a way to identify elements on a page.


 Locators are one of the essential components of Selenium infrastructure, which help Selenium
scripts in uniquely identifying the WebElements(such as text box, button, etc.) present of the web
page.
 Locator is a command that tells Selenium IDE which GUI elements ( say Text Box, Buttons,
Check Boxes etc) its needs to operate on.
Identification of correct GUI elements is a prerequisite to creating an automation script.
WebDriver uses the same set of locating strategies for specifying location of a particular web element.
Since, we are using WebDriver with java; each locating strategy has its own command in Java to locate the
web elements.

Note: Locating web elements in Webdriver is performed with the help of findElement() and findElements()
method.

Write some locator in selenium?

 ID
 Name
 Class name
 Tag name
 CSS Selector
 Link Text
 Partial Link text
 Xpath
 By ID - driver.findElement(By.id (<element ID>)) - Locates an element using the ID attribute
 By name - driver.findElement(By.name (<element name>)) - Locates an element using the Name
attribute
 By class name - driver.findElement(By.className (<element class>)) - Locates an element using
the Class attribute
 By tag name - driver.findElement(By.tagName (<htmltagname>)) - Locates an element using the
HTML tag
 By link text- driver.findElement(By.linkText (<linktext>)) - Locates a link using link text
 By partial link text - driver.findElement(By.partialLinkText (<linktext>)) - Locates a link using
the link's partial text

Describe Find Element in Selenium WebDriver?

We know that we use Selenium mostly for UI testing of a web-based application. Since we need to perform
automatic feature interaction with the web page, we need to locate web elements so that we can trigger
some JavaScript events on web elements like click, select, enter, etc. or add/ update values in the text
fields. To perform these activities it is important to first locate the element on the web page and then
perform all these actions.

There are differences between findElement and findElements method in Selenium webdriver. Both of them
can be used to locate elements on a webpage.

The findElement:
-used to uniquely identify a (one) web element within the web page.
- points to a single element
- the return type of findElement is a WebElement
- If there is no matching element, a NoSuchElementException is thrown by the findElement

Write down Gradle Vs Maven?

It is a build automation system that uses a Groovy-based DSL (domain-specific language )


It is a software project management system that is primarily used for java projects.
It does not use an XML file for declaring the project configuration.
It uses an XML file for declaring the project, its dependencies, the build order, and its required plugin.
It is based on a graph of task dependencies that do the work.
It is based on the phases of the fixed and linear model.
In Gradle, the main goal is to add functionality to the project.
In maven, the main goal is related to the project phase.
It avoids the work by tracking input and output tasks and only runs the tasks that have been changed.
Therefore it gives a faster performance.
It does not use the build cache; thus, its build time is slower than Gradle.

Gradle is highly customizable; it provides a wide range of IDE support custom builds.
Maven has a limited number of parameters and requirements, so customization is a bit complicated.
Gradle avoids the compilation of Java.
The compilation is mandatory in Maven.

Write down some of the test types that are supported by Selenium.

Different types of testing's that we can achieve through Selenium are.

o Functional Testing
o Regression Testing
o Sanity Testing
o Smoke Testing
o Responsive Testing
o Cross Browser Testing
o UI testing (black box)
o Integration Testing

Write down some Interacting command with web elements?


There are only 5 basic commands that can be executed on an element.

get()
get.title()
sendkeys()
findElement()
clear()
driver.close()
driver.quit()
element.submit() - (only applies to form elements). submits the form (same as clicking the Submit
button).

You might also like