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

Java

The document provides an overview of key concepts in Java, including identifiers, tokens, constructors, data types, arrays, strings, and object-oriented programming principles. It discusses various Java features such as singleton classes, access modifiers, exception handling, and the collection framework. Additionally, it covers synchronization, threading, and the differences between related concepts like final, finally, and finalize.

Uploaded by

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

Java

The document provides an overview of key concepts in Java, including identifiers, tokens, constructors, data types, arrays, strings, and object-oriented programming principles. It discusses various Java features such as singleton classes, access modifiers, exception handling, and the collection framework. Additionally, it covers synchronization, threading, and the differences between related concepts like final, finally, and finalize.

Uploaded by

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

Java

1.What are Identifiers in Java?


To identify the element in a program.
Generally, name of the classes, name of the methods and name of the variables. Identifiers
should not start with numbers(digits).

2.What is Java Tokens?


Java tokens are
Identifiers (name of a class, method, variable)
keywords (static, this, void, super, main etc...)
operators (+, -, * ,% etc.)
literals (int i = 10) --everything is literal in this

3.What is super calling statement in Java?


To call the immediate super class constructor in the sub class constructor

4.What is singleton class in Java?


Singleton class in java allows us to create only one object to class it means restricting the
unnecessary object creation.

Advantage: It saves memory.


Singleton class will be achieved in two ways.

1)Early Initialization: object will be created at load time

Class Test
{
private static Test t = new Test ();
private Test () ---If it is not private any person creates more objects
{
}
public static Test getTest ()
{
return t;
}
}
2)Lazy Initialization: creation of object when required (Runtime creation)

Class Test
{
private static Test t = null;

private Test () --If it is not private any person creates more objects
{
}
private static test getTest ()
{
if(t==null)
{
t = new Test ();
}
return t;
}
}

5.What is Constructor and its types and its usage?


To simplify the initialization process constructor will come into picture.
 It is a special type of method in java
 A Constructor name must be same of Class name
 A Constructor will be called, when you create object for class
 Constructor (without parameter, with parameter)
 Constructor is a non-static method because we cannot see any static keyword with it.
 A Constructor will be useful in PAGE OBJECT MODEL to call the elements to tests
 A Constructor can be overloaded.
 A Constructor cannot be overridden because when you try to call super class
constructor in sub class then compiler treat this as a method and expect return type but
constructor does not return any return type so we get compile error.

6 What are Primitive and Non-Primitive data types?


Primitive types are predefined (already defined in java), byte, int, long, short, float, double, char
etc.
Non-Primitive types are created by the programmer and is not defined by Java, Class, Interface,
Array, variable
String in java is a non-primitive data type because it refers to an object. The string object has
methods that are used to perform certain operations on strings.
7)Array/Collection:
Array: Collection of similar objects to be stored
Array Problems: Type problem: Once you declare any datatype then it cannot allow other
datatype values. But if you want to store different datatype element we should use object[].
Size problem: Once you declare size of an array while creating then the size is fixed it cannot
increase

Single Dimensional Array:


int a [] = new int[5];
String [] s= {rk, pk};
int [] i= {1,5,9};
Storing order problem:

Double Dimensional Array: it stores the values in the form of row and column.
int a [][] = new int [][];

7.What is String?
A string is a collection of characters which comes from java. lang. string package and it is
immutable because immutable cannot be changed and another reason why string is immutable
could be it is used in HashMap technique as key.

Why String is Immutable?


 Because immutable objects cannot be changed.
 Another reason of why String class is immutable could be due to HashMap. Since Strings
are very popular as HashMap key,
 it's important for them to be immutable so that they can retrieve the value object which
was stored in HashMap.
 String is used in different places like username and password etc.
 If String is mutable any hacker can change the String value encrypted or decrypted in
the that scenario security is compromised
 String can be created using two ways:
1)new keyword,2) literal.

Literal: String str = "hello"//stored in string pool.


String str1=new String("hello")//stored in heap memory.
Literals can be compared (we are not comparing same content comparing hash codes) using ==
but not with (new keyword)
e.g.: String str="Hello";
String str1="Hello";

if (str == str1)
{
}
e.g.: String str = new String("hello");
String str1 = new String("hello");

if (St. Equals(str1))
{
}

String Methods:
=============
 equals()
 equalsIgnoreCase()
 contains()
 charAt()
 toUpperCase()
 toLowerCase()
 replace(old,new)
 trim()
 IsEmpty()
 endsWith()

8.What is diff between String Builder and String Buffer?

String Buffer String Builder


1.It is synchronized and thread safe by default It is not thread safe.
2.It will be used where multiple threads are working on a String Used for single thread
Environment.
3.It is slow because of multiple thread synchronization Its fast because of single
Thread environment

9.ENUM: It’s a special class which represents group of constants.

By default, these constants are public static final.


e.g.:
enum Level
{
LOW,
MEDIUM,
HIGH
}
If I want to access these values in other class.
class EnumDemo
{
public static void main (String [] args)
{
Level myvar = Level.MEDIUM;
System.out.println(myvar);
}
}
output:MEDIUM

10.Syntax for Database Connection:

Class.forName("org.mariadb.jdbc.Driver"); //to load the driver


Connection con=DriverManager.getConnection("url","username","pwd"); //to create
connection for drivermanager
Statement stmt=con.createStatement();//which is used to execute sql query
ResultSet rs=stmt.executeQuery(select * from emp) //ResultSet used to store the result of SQL
while(rs.next())
{
String myName=rs.getString(2);
}
con.close();

11.Wrapper class: Conversion of primitive data type to object called W-Class


example:int to Integer, char to Character

Example:
int x=30; // primitive datatype
Integer y=x; //Wrapper class
The reason java is not 100% oop language its 99% only because primitive datatypes are not
object oriented which derived from C language to make it 100% oop language we will use
wrapper classes.
We will use in Collection concept as well

12.Object Oriented Programming Language


===============================
POLYMORPHISM (Method overloading, Method Overriding)
ABSTRACTION
ENCAPSULATION
INHERITANCE

POLYMORPHISM: One task can be performed in different ways and a polymorphism can be
achieved by using Method overloading, Method Overriding.

Method Overloading: A method can be same name with different parameter list (Achieved
while performing login functionality in the project)
Method Overriding: Duplicate method in child class will override the method in parent class.

ABSTRACTION: An Abstraction is nothing but hiding internal details of an application and


showing only functionalities to the user.
Example: When I was working with my project, I used Page object model generally we write
elements in pages and call to tests here we are hiding elements not showing in tests
Real World Example: ATM Machine It cannot show how the internal logic is implemented inside
machine it shows only functionality how to draw the money it’s called abstraction.

INHERITANCE: Acquiring the properties from parent to child called inheritance by using extends
Keyword we can achieve inheritance.
Example: Generally, we extend the base class (Which has browser initialization and invoking to
URL codes) in real time scenarios when we work with framework
Usage: Code reusability.

Single Inheritance (One Super class one Sub class)


Multiple Inheritance (More than one Super class and one Sub class but JAVA doesn’t support it
because we cannot extend two classes at the same time but it can be achieved by using
Interface concept here, we can implement more than one Super class in sub class)
Multi-Level Inheritance (One Super class and One Sub class and this Sub class can be act as
Super class for another sub class)
Hierarchical Inheritance (One Super class more than one Sub class)
Hybrid Inheritance (Combination of Hirarchical+Multi Level)

ENCAPSULATION: Encapsulation is the act of wrapping up of attributes (represented by data


members) and operations (represented by functions) under one single unit (represented by
class).

"Wrapping of data into one single unit"


Example CLASS, Which wrappers variables and methods into it.

Encapsulation also called data hiding it can be achieved by using private, getter and setter
methods (I have declared username, password elements as private in the @FindBy and
achieved these by using getter and setter methods)

13.Synchronization: It’s the concept where multiple threads trying to access same object at the
same time which leads to Data Inconsistency problem.
To solve this Data Inconsistency problem Synchronization will come into picture

By using synchronized keyword, we can handle this in 2 ways:


i) using synchronized method:
synchronized methodName ()
{
body of the method
}

If you want to synchronize only few lines of code then go for this synchronized block.
ii)using synchronized block:
synchronized(this)
{
body of the block
}

14. Thread: its light weight sub part of process (Thread is a smallest part of the program)
it will control by programmers.

Process: A program in execution is often referred to as process here threads are subpart of the
process.
it will control by operating system.

Narrowing-- (higher to lower data type conversion) (explicit type casting)


E.g.: Narrowing (double to int)
Double d = 458.45;
Int I = (int)d;

Widening-- (lower to higher data type conversion) (implicit type casting)


E.g.: Widening (int to double)
Int i=30;
Double d = I;

15. public static void main (String args [])


The args is an array of string type it contains the command line arguments that we can pass
while running the program.

16.What are Access modifiers in java and explain their scope?


public, private, protected and default
If you cannot declare any access modifier it is default (Scope within the package)
Public (Scope within project)
Private (Scope within class)
Protected (Within class and applicable to sub classes as well if you extended it)

17. What is Abstract class and Abstract methods and how it is useful?
Abstract class: It is the class which has
Abstract methods (Just method declaration no definition) and
Non abstract methods (General methods)

Abstract method: Just method declaration no definition

Example: public abstractclass Example


{
public webDriver driver;
public void openUrl () //Non-Concrete method
{
driver.get ("");
}
public abstract void getTitle(); //Abstract method
}

public ChildClass extends Example


{
@override
public void getTitle()
{
drivet.getTitle();
}
}

18.What is Interface in java and what makes it so useful?


 An Interface is a blue print of a class
 There are mainly two reasons to use interface. They are given below.
 It is used to achieve 100% abstraction. (because it supports only abstract methods (just
declaration no definition))
 By using interface, we can support the functionality of multiple inheritance (we can
implement two or more than parent classes for single child class)

19.What are SUPER, STATIC, THIS, FINAL Keywords in java?


1)SUPER keyword: It is used to call Super class method or variable. When Super class method
name or variable name and Sub class method or variable name are same

2)STATIC keyword: Used for memory management and we save the memory because we no
need to create object to call either static method/variables. Static can be referred to the
common property
Static methods cannot be overridden.

3)THIS Keyword: Which is used to access current class objects this keyword will be used where
the scenario instance variables and local variables are same

4)FINAL Keyword: Once we declare variable or method or class with final keyword it is final, we
cannot change it.

20.What is the difference among final, finally and finalize?


final is keyword it will be used for class, method and variable. Once you declare any of these as
final it cannot be overridden, cannot be inherited, cannot be changed the values.

finally, is a block it will execute irrespective of exception is handled or not.

finalize is a method is used to perform cleanup processing before object is garbage collected.
21.What is Exception and its hierarchy?
Exception class is a subclass of Throwable class and other than exception class there is another
subclass that is Error.
Error: An Error is abnormal condition that happens because of failures and it cannot be handled
by the Java programs.
E.g.: JVM is run out of memory normally programs cannot recover from it.

An Exception is an abnormal condition which stops normal flow of an execution.


Generally, there are types exceptions
1)Checked exceptions (Compile time exception):
This can be handled by using try-catch block and throws keyword

try-catch applied at the code level


throws applied at the method level
finally, block is optional either use it or leave it but it always executes

Examples:
FileNotFoundException
InterruptedException
IOException

2)Unchecked exception (Run time exception)


Handled only by using try-catch block.

Examples
SessionNotCreatedException
StaleElementReferenceException
NoElementFoundException

22.Difference between throw and throws?

Throw Throws
Throw is a keyword used to throw an throws is a keyword used in the method
Exception explicitly within the function signature used to declare an exception
Which might get thrown by the function
while executing the program.
23. Why JAVA has both Compiler and Interpreter?
Because the source code is first compiled into binary byte code then this byte code runs on JVM
which usually software-based interpreter.

Collections
It’s a Framework where group of objects to be stored, manipulated and deleted
Collection--Interface whereas Collections--Class

Why collection came into picture means before collection we had concept of Arrays but with
arrays, we had some problems those are

1-Size problem
2-Type Problem

Size Problem: Once you declare size of an array it cannot be changed


Type Problem: By using Arrays we can store only similar datatype elements only

Collection Framework: -
----------------------
LIST(I)--which allows duplicates, Maintain Insertion order
SET(I)---Which does not allow duplicates, does not maintain insertion order
QUEUE(I)--FIFO

LIST---Array List(C), LinkedList(C), Vector(C), Stack(C)

SET---HashSet(C), LinkedhashSet(C), Sorted Set(I), Tree Set(C)

MAP---Represents elements in the form of Key-Value Pair--does not allow duplicates


Hashmap, Tree map, Hash table

Why MAP does not extend the collection Interface?


The main reason why MAP doesn’t extend the collection Interface is that the add (E e) method
of the collection interface does not support the Key-Value pair like MAP interface's put (k, v)
method.

Comparable, Comparator--Both are used to Sort the elements in collection but the difference is
Comparable will do the default sorting whereas Comparator will do the customized sorting.
Array List: It’s a class and dynamic array in nature (resizable or growable array in size)
--It contains duplicate values
--It maintains insertion order
--NULL Insertion is possible
--Array List is better for Storing and Accessing data (because it implements RandomAccess
Interface)
--It creates an empty array list object with default initial capacity 10 once it reaches to full then
automatically it increases its size with 50% capacity
--How to make Array List Synchronized?
--Non-Synchronized:
ArrayList al = new ArrayList ();
--Synchronized
List I = Collections.synchronozedList(al);

LinkedList: It’s a class internally it uses double linked list


--It contains duplicate values
--It maintains insertion order
--NULL Insertion is possible
--LinkedList is better for manipulating (Insertion and deletion) because no bit shifting is
Required
--Usually, we can use LinkedList to implement stacks and queues to provide support for this
requirement LinkedList class defines following specific methods

void addFirst();
void addLast();
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();

Vector: It’s a legacy class resizable or growable array its synchronized and thread safe compare
with Array List and uses some old methods
--It contains duplicate values
--It maintains insertion order
--NULL Insertion is possible
Methods uses in Vector class:
addElement ()
removeElementAt ()
removeAllElements ()

Stack: It’s a child class of vector and specially designed for Last In First Out order (LIFO)

Methods available in Stack:


Push () --for insertion
POP () --for retrieval
Peek () --to retrieve penultimate element from Stack

You might also like