Sunteți pe pagina 1din 28

OOPS Java

Abstraction: is a process of hiding the implementation details and showing only


functionality to the user.

Use:

Abstract Class: A class which contains the abstract keyword in its declaration is
known as abstract class.

Use: Let’s say we have a class Animal that has a method sound() and the
subclasses(see inheritance) of it like Dog, Lion, Horse, Cat etc. Since the animal
sound differs from one animal to another, there is no point to implement this
method in parent class. This is because every child class must override this
method to give its own implementation details, like Lion class will say “Roar” in
this method and Dog class will say “Woof”.

Abstract methods: An abstract method is a method that is declared without an


implementation (without braces, and followed by a semicolon), like this:

Ex: abstract void moveTo(double deltaX, double deltaY);


Use:

Abstract class: An abstract class is a class that is declared abstract—it may or


may not include abstract methods. Abstract classes cannot be instantiated, but
they can be subclasses.
Use:

Interfaces: An interface is a blueprint of class. It has constants and abstract methods.

Use:
i. It is used to achieve total abstraction.
ii. Since java does not support multiple inheritance in case of class, but by using
interface it can achieve multiple inheritance .
iii. It is also used to achieve loose coupling.
iv. Interfaces are used to implement abstraction. So the question arises why use
interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas
variables in interface are final, public and static.
Ex:
Encapsulation: The process of binding the group of data within a single unit of class
Use:

Tightly encapsulated class: the class conations private properties class said to be
tightly encapsulation.

Use:

Polymorphism: One person but different behavior or Polymorphism is one of


the OOPs features that allow us to perform a single action in different ways.

Use:

Types of Polymorphism: 2 types of polymorphism

i. Compile time Polymorphism/static binding/early binding-Method


Overloading- mapping will be done in compile time.

ii. Runtime Polymorphism/Dynami binding/late binding-Method


Overriding

Use:

Method Overloading: In a class same method and different arguments.


Use:

Method Overriding: In a class same method and same arguments


Use:

Inheritance: The ability to create classes that shares the attributes and methods
of existing classes.

Use: Inheritance is a parent-child relationship of a class which is mainly used for code reusability
Types of Inheritance:

Use:

Constructors: A constructor is an instance method that usually has the same name
as the class.

Use: The purpose of constructor is to create object of a class

Types of Constructors: There are two types of constructors:

1. Default constructor (no-arg constructor)

2. Parameterized constructor
Use:

Collections: A Collection is data structure which holds elements as group.

Collections framework: is a framework that provides an architecture to store and


manipulate the group of objects.
Use:

Array List: Java ArrayList class uses a dynamic array for storing the elements. It inherits
AbstractList class and implements List interface.

Use:

import java.util.*;
class TestCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
} } }

Difference between Arrays and collections:

Arrays:

Fixed in size

W.r.t memory arrays are not recommended.

W.r.t performance good.

We can hold objects and primitives

Collections:

Grow bale in nature

W.r.t memory arrays are recommended.

W.r.t performance not good.

We can hold only objects not primitives


Java HashMap class:

HashMap is a Map based collection class that is used for storing Key & value pairs, it is
denoted as HashMap<Key, Value> or HashMap<K, V>. ... It does not sort the stored
keys and Values. You must need to import java.util.HashMap or its super class in order
to use the HashMap class and methods.

Ex:
Note:

The important points about Java HashMap class are:

o A HashMap contains values based on the key.

o It contains only unique elements.

o It may have one null key and multiple null values.

o It maintains no order.

Java Hashtable class

Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.

The important points about Java Hashtable class are:


o A Hashtable is an array of list. Each list is known as a bucket. The position of bucket
is identified by calling the hashcode() method. A Hashtable contains values based on
the key.

o It contains only unique elements.

o It may have not have any null key or value.

o It is synchronized.

Ex:
Difference between HashSet and HashMap

HashSet contains only values whereas HashMap contains entry(key and value).
List Vs Set:

List is an ordered collection it maintains the insertion order, which means upon
displaying the list content it will display the elements in the same order in which they
got inserted into the list.

Set is an unordered collection, it doesn’t maintain any order. There are few
implementations of Set which maintains the order such as LinkedHashSet (It maintains
the elements in insertion order.

List allows duplicates while Set doesn’t allow duplicate elements.

When to use Set and When to use List?

The usage is purely depends on the requirement:

If the requirement is to have only unique values then Set is your best bet as any
implementation of Set maintains unique values only.

If there is a need to maintain the insertion order irrespective of the duplicity then List is
a best option. Both the implementations of List interface – ArrayList and LinkedList
sorts the elements in their insertion order.

Methods: A Java method is a collection of statements that are grouped together


to perform an operation.

Use:

Aggregation: If a class have an entity reference, it is known as Aggregation. Aggregation


represents HAS-A relationship.

Consider a situation, Employee object contains many informations such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such
as city, state, country, zipcode etc. as given below.

Use: For Code Reusability.

class Employee{
int id;
String name;
Address address;//Address is a class
...
}
Association: Association is relation between two separate classes which establishes
through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-
many.
In Object-Oriented programming

Use:

Object: Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance
of a class.
Use:

Class: A class can be defined as a template/blueprint that describes the behavior/state


that the object of its type support.
Use:

String: The String class is used to manipulate character strings that cannot be
changed. Simply stated, objects of type String are read only and immutable.

Use:

String Buffer: Java StringBuffer class is used to create mutable (modifiable) string. The
StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

Use:

Difference between String and StringBuffer:

No. String StringBuffer

1) String class is immutable. StringBuffer class is mutable.


String s = new String("Hari"); StringBuffer sb = new StringBuffer("Hari");
s.concat("Krishna"); sb.append("Krishna");
System.out.println(s);Output: Hari System.out.println(sb); Output:Harikrishna

2) String is slow and consumes more StringBuffer is fast and consumes less memory
memory when you concat too many when you cancat strings.
strings because every time it creates
new instance.
3) String class overrides the equals() StringBuffer class doesn't override the equals()
method of Object class. So you can method of Object class.
compare the contents of two strings
by equals() method.

Note: String: once create string object we can’t perform any change in the existing object
and if trying to perform any changes with those changes a new object will be created.

Ex: S- Hari-, for new object created-Harikrishna-will be garbage collections

Note: String Buffer: once we create a string buffer object we can perform any type of
changes in the existing object this changeable behavior mutability.

Ex: by default we will get Harikrishna in StringBuffer.

Note: String is an immutable class, it can't be changed. StringBuilder is a mutable


class that can be appended to, characters replaced or removed and ultimately converted to
a String StringBufferis the original synchronized version of StringBuilder
You should prefer StringBuilder in all cases where you have only a single thread accessing
your object.
String Methods: String is a sequence of characters. But in Java, a string is an object that
represents a sequence of characters. The java.lang.String class is used to create string object.

There are two ways to create a String object:

1. By string literal : Java String literal is created by using double quotes.


For Example: String s=“Welcome”;
2. By new keyword : Java String is created by using a keyword “new”.
For example: String s=new String(“Welcome”);
It creates two objects (in String pool and in heap) and one reference variable where
the variable ‘s’ will refer to the object in the heap.
i. length():The Java String length() method tells the length of the
string. It returns count of total number of characters present in the
String.
ii. compareTo():The Java String compareTo() method compares the
given string with current string. It is a method
of ‘Comparable’ interface which is implemented by String class. It
either returns positive number, negative number or 0
iii. concat():The Java String concat() method combines a specific string
at the end of another string and ultimately returns a combined string.
It is like appending another string
iv. IsEmpty():This method checks whether the String contains anything
or not. If the java String is Empty, it returns true else false
v. Trim() : The java string trim() method removes the leading and
trailing spaces. It checks the unicode value of space character
(‘\u0020’) before and after the string. If it exists, then removes the
spaces and return the omitted string
vi. toLowerCase() : The java string toLowerCase() method converts all
the characters of the String to lower case
vii. toUpper() : The Java String toUpperCase() method converts all the
characters of the String to upper case
viii. ValueOf(): This method converts different types of values into
string.Using this method, you can convert int to string, long to string,
Boolean to string, character to string, float to string, double to string,
object to string and char array to string. The signature or syntax of
string valueOf() method
ix. replace(): The Java String replace() method returns a string,
replacing all the old characters or CharSequence to new characters
x. contains() :The java string contains() method searches the sequence
of characters in the string. If the sequences of characters are found,
then it returns true otherwise returns false
xi. equals() : The Java String equals() method compares the two given
strings on the basis of content of the string i.e Java String
representation. If all the characters are matched, it returns true else it
will return false
xii. equalsIgnoreCase(): This method compares two string on the basis
of content but it does not check the case like equals() method. In this
method, if the characters match, it returns true else false
xiii. toCharArray(): This method converts the string into a character
array i.e first it will calculate the length of the given Java String
including spaces and then create an array of char type with the same
content
xiv. GetBytes() : The Java string getBytes() method returns the sequence
of bytes or you can say the byte array of the string
xv. endsWith() : The Java String endsWith() method checks if this string
ends with the given suffix. If it returns with the given suffix, it will
return true else returns false
xvi. toString ():In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. ...
The toString is the function called whenever java needs the string
representation of an object of your class
xvii. charAt():The charAt() method returns the character at the specified index in
a string. The index of the first character is 0, the second character is 1, and
so on.
xviii. indexOf(): This method returns the index within this string of
the first occurrence of the specified character or -1, if the character does
not occur

Multithreading: Multithreading in java is a process of executing multiple threads


simultaneously

Use: Used to achieve multitasking.

Exceptions: An Exception is an event, which occurs during the execution of a


program, that disrupts the normal flow of the program’s instructions or in simple words,
any issue which makes your test case stop in between the execution is an Exception.

Difference between Error and Exception:


An Error “indicates serious problems that a reasonable application should not try to
catch.”
An Exception “indicates conditions that a reasonable application might want to catch.”

Use:

Throw exception: Throw: Sometimes we want to generate exception explicitly in our


code, for example in Selenium Automation Framework most of the time we print self-
written logs, once we catch an exception and then we need to throw that exception
back to the system so that the test case can be terminated. Throw keyword is used to
throw exception to the runtime to handle it.

Throws: When we are throwing any exception in a method and not handling it, then
we need to use throws keyword in method signature to let caller program know the
exceptions that might be thrown by the method.
Use:

Public: To call by JVM from anywhere

Use:

Static: Static keyword in java is mainly used to save memory as with the help of static
we can declare data one time and access it in a whole program where we need the
same data more than one time in a program. After creating static keyword there is no
need to declare that data again and again. Static keyword can be used with:

 Nested class
 Method
 Variable

Use:

Non-static: Memory for non-static variable is created at the time of create an object of
class. These variable should not be preceded by any static keyword Example: These
variables can access with object reference.

Use:

Void: main method won’t return anything to JVM that’s why void It will not return any
return type.

Use:

Main: Won’t checked by compiler at runtime but JVM Check runtime for method inside
the class or not.

Use:

Access specifies: Public, private, protected, default, final, static, abstract,


synchronized.. These are called as modifiers in java not specifiers
Use:

Singleton Class: Singleton Pattern says that just"define a class that has only one instance and
provides a global point of access to it".

Use:

Method signature: Method signature means method name(main-m1) and parameters


list is called method signature

Use:

THIS keyword:

 It can be used to refer current class instance variable


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

Use:

Super keyword: The super keyword in java is a reference variable which is used to refer
immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Use:

1. super can be used to refer immediate parent class instance variable.

2. super can be used to invoke immediate parent class method.

3. super() can be used to invoke immediate parent class constructor.

Packages: A Java package is a mechanism for organizing Java classes. Package are used in Java, in-
order to avoid name conflicts and to control access of class, interface and enumeration

Use:
Garbage collection: The garbage collector is a program which runs on the Java Virtual
Machine which gets rid of objects which are not being used by a Java application anymore.
It is a form of automatic memory management

Use:

Try-catch: The try block contains set of statements where an exception can occur. A try
block is always followed by a catch block, which handles the exception that occurs in
associated try block. A try block must be followed by catch blocks or finally block or both.

A catch block is where you handle the exceptions, this block must follow the try block

Use:

Checked exceptions: Checked Exceptions are checked at compile time only, these are
must and should handle by the programmer.

Ex: IOException, FileNotFoundExpection,ClassNotFoundException

Use:

Unchecked exceptions: Unchecked exceptions are not checked by compiler at the


time of compilation. the exceptions which are extended by RuntimeException.

Ex: AritmeticException, NullPointerException

Use:

What is Assertion:
Asserts helps us to verify the conditions of the test and decide whether test has
failed or passed.

Ex:

@Test public void testCaseVerifyHomePage() {

driver= new FirefoxDriver();

driver.navigate().to("http://google.com");
Assert.assertEquals("Google", driver.getTitle()); }

Note:

There are other assert methods that could be used to verify the text in place of
assertEquals()
assertTrue(strng.contains(“Search”));
assertTrue(strng.startsWith(“Google”));
assertTrue(strng.endsWith(“Search”));
Array vs ArrayList:

---Array: index based

Array is used represent a group of elements in a single element and this elements must be homogenous
and must fixed number.

Simple fixed sized arrays that we create in Java, like below

i. declare an array: int[] a;


ii. instantiations: object creation: a = new int[4];
iii. initialization: assign the values: a[] = 10; a[1] = 20..
iv. int[] a = {10,20,…} direct method

int arr[] = new int[10]

package Sample;

public class Arrays {

public static void main(String[] args) {


// TODO Auto-generated method stub
int [] a = {10,20,30};

String[] s = new String[3];


s[0] = "Hari";
s[1] = "Krishna";
s[2] = "Challa";

for(String ss:s) {//for each loop to get all values from array

System.out.println(ss);
}

// 1st approach to print the data from array


System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);

//2nd approach to print the data from array

for(int i=0; i<a.length;i++) {

System.out.println(a[i]);
}
//3rd approach to print the data from array
for(int aa:a) { //a is reference variable * foreach loop
System.out.println(aa);
}
}

How to print null values from array:


Class: Emp
package Sample;

public class Emp {

int eID;
String ename;
Emp(int eID, String ename){
this.eID = eID;
this.ename = ename;

}
}

**********************************************************
Emp [] e = new Emp[5];
e[0] = e1;
e[1] = e2;
e[4] = e3;

for(Object o : e) {
if(o instanceof Emp) {
Emp E = (Emp)o;

System.out.println(E.eID +"*****"+ E.ename);


}
if(o==null) {
System.out.println(o);

-- ArrayList:
Dynamic sized arrays in Java that implement List interface.
ArrayList<Type> arrL = new ArrayList<Type>();

Ex: // A Java program to demonstrate differences between array and ArrayList;

class Test

public static void main(String args[])

/* ........... Normal Array............. */

int[] arr = new int[2];

arr[0] = 1;

arr[1] = 2;

System.out.println(arr[0]);

/*............ArrayList..............*/

// Create an arrayList with initial capacity 2

ArrayList<Integer> L = new ArrayList<Integer>(2);

// Add elements to ArrayList

L.add(1);

L.add(2);

// Access elements of ArrayList

System.out.println(arrL.get(0));

}
Difference between arraylist and linkedlist ?

S-ar putea să vă placă și