DevLabs Alliance Java For SDET
DevLabs Alliance Java For SDET
By DevLabs Alliance
SDET Professional Course Overview
• Duration – 12 weeks • High Level Curriculum
• Loop Control
❖ for
❖ while
❖ do while
❖ foreach
• Arrays
Core Java - Table of Contents
• Strings • Collections Framework
❖ Java String
❖ Creating String
• Q&A
❖ String Pool
❖ String Methods
❖ StringBuffer vs StringBuilder
❖ Wrapper Classes
• Exception Handling
❖ Exceptions
❖ Exception Hierarchy
❖ Errors vs Exceptions
❖ Exception Types
❖ Exception Keywords
❖ User-defined Exceptions
What is Java?
Java
▪ Java is an object-oriented programming
language which produces software for
multiple platforms.
● Similarly, classpath should be set to the lib folder of the installation directory :
C:\Program Files\Java\jdk1.8.0_151\lib
IDE
▪ A software suite that consolidates basic tools to write and test software.
▪ An IDE typically contains a code editor, a compiler or interpreter, and a debugger, accessed
through a single graphical user interface (GUI)
❏ A variable's name can be any legal identifier — a sequence of Unicode letters and
digits, beginning with a letter, the dollar sign "$", or the underscore character "_“.
❏ String 1EmpName is an invalid name for a variable. (cannot begin with a number)
❏ The convention, is to always begin your variable names with a letter, not "$" or "_“.
So, prefer String empName over String _EmpName.
Variables
Types of Variables
● Primitive data types: boolean, char, byte, short, int, long, float and double.
● Non-primitive data types: Strings, arrays etc.
18
Case Example
Suppose Priya, an employee at a Retail Store has to generate an invoice for a customer, Mac.
She needs to include the following fields in the invoice:
● Invoice No.
● Item No.
● Item Price
● Quantity of items purchased
● Discount
● Total Amount
● Comments
These are predefined words by Java so it cannot be used as a variable or object name.
Operators
Operator in java is a symbol that is used to perform operations.
There are mainly four categories of operators in Java.
Arithmetic Operators
Unary Operators
Relational Operators
Logical Operators
Arithmetic Operators
! Logical negation !x
Relational Operators
Operator Meaning Usage Example Meaning
Expression Value
(first+second)/2 - third 3
first++ 7
! flag true
Case Example
Priya needs help again! This time, she has to generate invoice for Alex who has bought three
items from the store in specific quantities, with the prices as below:
Item B 80 5 units
She needs to give the 15% discount on all items as there is a sale on.
Also, she needs to add 2% service tax in the bill.
▪ Instance of a class.
Example: When you call the System.out.println() method, for example, the system actually
executes several statements in order to display a message on the console.
Example:
public static int getProduct (int a, int b) public static : access modifier.
{ int: return type
return (a*b); getProduct: name of the method
} a, b: parameters
Constructors
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, a constructor is called.
Constructors have no explicit return type and they always have the same name as the class.
All classes have constructors, whether you define one or not, because Java automatically
provides a default constructor that initializes all member variables to zero. However, once you
define your own constructor, the default constructor is no longer used.
▪ Classes in the same package can access each other's protected members.
▪ Classes need to be referred using its complete name (package + class name): for example,
java.util.Calendar
▪ Packages can be “imported” to avoid writing package names every time you use * instead
of class name.
import java.util.*;
The access modifiers in java specify accessibility (scope) of a data member, method,
constructor or class.
● private
● default
● protected
● public
Case Example
Let us define a Product class and instantiate it.
We will set its attributes and define its behaviour using constructors and
member functions.
Lab 2
3. Define a class and create its objects, define its attributes, constructors and
member functions.
OOPS
Concepts
Encapsulation
Encapsulation is one of the four fundamental OOPS concepts. The other three are Inheritance,
Polymorphism, and Abstraction.
Encapsulation simply means binding object state (fields) and behaviour (methods) together. If you
are creating a class, you are doing encapsulation.
This way data can only be accessed by public methods thus making the private fields and their
implementation hidden for outside classes. That’s why encapsulation is known as data hiding.
Inheritance
▪ A mechanism in which one object acquires all the properties and behaviors of the parent
object.
▪ The extends keyword indicates that you are making a new class that is built on top of an
existing class.
▪ There is a parent-child relationship among the two classes, depicted by IS-A relation.
▪ A class A that is inherited is called the super class. The class B which extends A, is called a
subclass, So, B is A.
Hierarchical
Class C Inheritance
Single level
Inheritance
Multi-level
Inheritance
Abstraction
A process of hiding the implementation details and showing only the functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it.
//body
● if
● if-else
● if-else-if
● nested-if
● switch-case
If Statement
if(condition)
{
// Statements to execute if condition is true
}
If-else Statement
if (condition)
{
// Executes this block if condition is true
}
else
{
// Executes this block if condition is false
}
If-else if Statement
If-else-if statement is used when we need to check
multiple conditions.
We have only one “if” and one “else”, however we
can have multiple “else if”. It is also known as if else
if ladder.
if(condition_1) {
/*if condition_1 is true execute this*/
statement(s);
}
else if(condition_2) {
/* execute this if condition_1 is not met and
* condition_2 is met
*/
statement(s);
}
else{
statement(s); //if none of the condition is true
* then these statements gets executed
}
Nested if Statement
A nested if is an if statement that is the target
of another if or else.
Nested if statements means an if statement
inside an if statement.
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Switch case Statement
● Evaluates the expression and compares with values of each case label.
● Executes all statements of the matching case label.
● The break statements are important because if they are not used, all statements after the
matching case label are executed in sequence until the end of switch statement.
switch (variable/expression)
{
case value1:
// statements
break;
case value2:
// statements
break;
.. .. ...
.. .. ...
default:
// statements
}
Lab 4
1. Write a program to print the largest of three numbers using if-else if
1. Write a program to check whether the no. entered from user is positive or
negative.
Loop Control
for Loop
for(initialization; condition ; increment/decrement)
{
statement(s);
}
class ForLoopDemo
{
public static void main(String args[])
{
for(int i=10; i>1; i--)
{
System.out.println("The value of i is: "+i);
}
}
}
while Loop
while (testExpression)
{
// codes inside body of while loop
}
class WhileLoopDemo
{
public static void main(String args[])
{
int i=10;
while(i>1)
{
System.out.println(i);
i--;
}
}
}
do-while Loop
do {
// body of do while loop
} while (testExpression);
class DoWhileLoopExample
{
public static void main(String args[])
{
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
}
for-each Loop
In Java, there is another form of for loop (in addition to standard for loop) to work with arrays and
collection, the enhanced for loop.
for(data_type variable : array | collection)
{ for (type var : array)
//body of for-each loop {
} statements using var;
}
class ForEachDemo
{
is equivalent to:
public static void main(String[] args)
{ for (int i=0; i<arr.length;
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; i++)
{
for (char item: vowels)
type var = arr[i];
{ statements using var;
System.out.println(item);
}
}
}
}
Loop Control Statements
Statement Description
Continue Causes the loop to skip the remainder of its body and immediately retest its
condition prior to reiterating.
Break Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
Lab 5
1. Write a number to print the table of 5, first 10 values.
2. Write a program to display prime numbers between two numbers where you
get the 2 inputs for the range, from the user.
Lab 5
A college professor is trying to compute marks and grades for her class of 60 students. There are
5 subjects that she needs to mark them on and then, accordingly print their grades.
Lets see how we can help her using loops and conditional statements.
The five subjects are :
40-60 Average
60 to 75 Good
▪ 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.
Types of Arrays
Single-dimensional Array
Multi-dimensional Array
Initialization
Index in Y dimension
0 1 2 3 4
Value 12 24 45 68 90 0 2 23 12 54 42
Index in
1 6 21 14 53 65
X
Index d[0] d[1] d[2] d[3] d[4] dimension 2 28 1 17 7 34
3 25 5 8 62 26
Array Examples
Priya needs help again...this time she wishes to store invoices of 20 customers with the
amount of each and the invoice number, but she wants to store them together in one
place.
A series where the next term is the sum of previous two terms.
The first two terms of the Fibonacci sequence is 0 followed by 1.
The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
4. Write a program to check current year is leap year or not. User will enter year value.
6. Write a program to calculate area of triangle. User will enter the values for base and
height of the triangle.
71
Assignment 1
7. Write a program to print the sum of first 20 natural numbers.
8. Write a program to reverse the elements of an array where the array size as well as the
array values are entered by the user.
❏ For a single alphabet or letter, we have char data type but we need to store data like words,
sentences or paragraphs, we need Strings.
❏ String is a built-in class used to create, process and manipulate Strings in java, it is in the
java.lang package.
74
String Class
java.lang.String
❖ By new keyword
String s = new String("Welcome");
char[] ch = {'j','a','v','a','p','o','i','n','t'};
String s = new String(ch);
Java String Pool refers to a collection of String literals which are stored in heap
memory.
String Pool helps in saving memory space for Java runtime.
76
String Pool
String str = “Hello World”; //String literal JAVA HEAP MEMORY
str3
String Literals are created only once.
Hello World
❖ They are shared, save memory space. str2
❖ They are constants. Hello World
str4
If String is created using new keyword,
a new object is always created in memory.
77
String is immutable
• String is immutable in nature, the data inside a String object cannot be changed.
• You can never modify a String object. A new object is always created that contains the
modified character sequence.
• You can perform various operations on String: like searching an alphabet or word in
sentences, dividing strings.
• You can’t use the relational or equality operators to compare the values stored in strings.
(You will compare the pointers, not the objects!)
78
String Methods
String Methods
char charAt(int index) returns char value for the particular index
length() returns string length
toLowerCase() returns formatted string
● equals()
● equalsIgnoreCase()
● compareTo()
● length()
● toUpperCase()
● contains()
● subString(int i)
● subString(int i, int j)
● replace()
● toCharArray()
● trim()
81
Lab 7
1. Write a program to sort the Strings in the array: (Bubble Sort)
String str[] = “Ciaz, Alto, Swift, Dezire, Brezza”
Try with user input also, using Scanner.nextLine()
2. Write a program to find the uppercase and lowercase characters in the string below.
String characters = "AbCdefGHijklMNOpqRstUVwxyZ@%*234";
Use char.isUpperCase(char c) and char.isLowerCase(char c)
4. Write a program to trim the String : " She sells sea shells on the sea shore ".
82
StringBuffer & StringBuilder
CharSequence
83
String Exercise 2
Let us further explore Strings:
● isEmpty()
● concat()
● StringBuilder : append()
● StringBuffer : append()
84
Wrapper Classes
Wrapper classes are used for converting primitive data types into objects, like int to Integer etc.
● int i = Integer.intValue()
● double d = Double.doubleValue()
Methods to parse Strings and convert to int/double etc. are parseXXX() and valueOf()
86
Exception Handling
Exceptions
An exception is an unwanted event that disrupts the normal flow of the program.
88
Exception Hierarchy
89
Errors vs Exceptions
Error Exception
90
Exception Types
EXCEPTIONS
➔ All exceptions other than Runtime ➔ Unchecked exceptions occur at the time
Exceptions. of program execution.
91
Exception Keywords
Keyword Description
try We place the code that throws exception inside the “try” block. A try block
must be followed by either a catch block or finally.
Can’t use try block alone.
catch “Catch” block is used to handle the exception. It must be preceded by try
block and can’t be used alone. Can be followed by finally block later.
finally “Finally” block is used to execute the important code of the program. It is
always executed whether an exception is thrown or not.
92
Basic Exception Format
class Exception
{
public static void main(String args[])
{
try
{
//code that may throw exception
}
catch(Exception e)
{
// exception-handling code
}
finally
{
//important code : always executed
}
93
Lab 9
1. Write a program with try, catch and finally block.
94
Exception Propagation
An exception is first thrown from the top of the stack and if it is not caught, it drops
down the call stack to the previous method,If not caught there, the exception again
drops down to the previous method, and so on until they are caught or until they
reach the very bottom of the call stack.This is called exception propagation.
95
Things to Remember
➔ You can have nested try blocks also, i.e. one try catch block inside an outer try block.
➔ Any number of catch methods may follow a try block. (Multiple catch blocks)
If one handler code inside catch is executed, All other catch methods are ignored.
➔ When an exception occurs, these are scanned in order, to find a matching parameter. The
more specific ones should be placed first and then the most generic Exception should be
placed at last.
➔ There are many rules if we talk about method overriding with exception handling.
If the superclass method does not declare an exception
○ If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but it can declare unchecked exception.
If the superclass method declares an exception
○ If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.
96
Throw vs throws
Throw Throws
Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
an exception. exception.
Checked exception cannot be propagated Checked exception can be propagated with
using throw only. throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions.
Example : public void method() throws
IOException,SQLException.
97
Final vs finally vs finalize
Final Finally Finalize
Garbage collection in Java happens automatically during the lifetime of the program,
eliminating the need to deallocate memory and thereby avoiding memory leaks. All
unreferenced objects’ memory is reclaimed.
Explicit call : System.gc()
98
Java Custom Exceptions
If you are creating your own Exception that is known as custom exception or
user-defined exception.
Java custom exceptions are used to customize the exception according to user need.
Java custom exception class must extend Exception class.
99
Lab 10
1. Write a program where a user-defined exception is thrown.
100
Assignment 2
1. Write a program to print the occurrence of each character in the String
DevLabsAlliance Training
3. Write a program to check “brown” is present in the string : A brown fox ran away fast
4. Write a program to convert String to a character array and character array to String.
5. Write a program to count the repeated occurrences of a character in a String and print
all the repeated characters.
101
Assignment 2
8. Write a program with nested try blocks.
10. Write a program where you pass an argument while throwing an exception.
102
For any open questions, be in touch with us at training@devlabsalliance.com
Visit us at www.devlabsalliance.com
Collection Framework
Collections Framework
Collections are the containers that groups multiple items in a single unit.
Using Java Collections, various operations can be performed on the data like searching,
sorting, insertion, manipulation, deletion etc.
Collections Framework provides many interfaces and classes in java.util package, with
tons of useful functions, to process the data efficiently.
Collections Hierarchy
107
List Interface
● List is a data structure in which we can store the ordered collection (a sequence) of objects.
● It can have duplicate values.
● Lists can be empty – no elements.
● List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
108
List Interface : Methods
Method Description
add(int index, E element) It is used to insert the specified element at the specified position in a list.
remove(int index) It is used to remove the element present at the specified position in the list.
subList(int frmIndex, int toIndex) It is used to fetch all the elements lies within the given range.
indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified
element, or -1 if the List does not contain this element.
equals(Object o) It is used to compare the specified object with the elements of a list.
get(int index) It is used to fetch the element from the particular position of the list.
toArray() It is used to return an array containing all of the elements in this list in the
correct order.
109
ArrayList
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess,
Cloneable, Serializable
LinkedList is a list implementation where the elements are linked with each other using pointers.
● It can contain duplicate elements.
● It also maintains insertion order.
● It is non synchronized.
● Manipulation is fast because no shifting needs to occur.
We can add or remove elements from one end. We can add or remove elements from both sides.
ArrayList vs
ArrayList LinkedList
LinkedList
Implements list as an array Implements list as a doubly-linked list with a header
node.
Provides random access to all elements No random access, needs to traverse to access the ith
element.
Insertion and removal required shifting of subsequent Insertion and removal done by rearranging the links - no
elements. shifting
Needs to be resized when out of space. Nodes are allocated and removed as necessary.
112
ArrayList vs
Vector
ArrayList and Vector both implement the List interface and maintain insertion order.
ArrayList Vector
Grows by 50% if the number of elements exceeds Vector grows by 100%, i.e. doubles itself if the number
from tis capacity. of elements exceeds from tis capacity.
113
Iterator vs ListIterator
114
Lab 10
Write Java programs to:
115
List Iterator Interface
ListIterator Interface is used to traverse the elements in a backward and forward direction.
boolean hasNext() This method returns true if the list iterator has more elements while traversing the list in
the forward direction.
E next() This method returns the next element in the list and advances the cursor position.
boolean This method returns true if this list iterator has more elements while traversing the list in
hasPrevious() the reverse direction.
E previous() This method returns the previous element in the list and moves the cursor position
backward.
void remove() This method removes the last element from the list that was returned by next() or
previous() methods
void set(E e) This method replaces the last element returned by next() or previous() methods with the
specified element.
116
Collections Class
public class Collections extends Object
Java collection class is used exclusively with static methods that operate on or return collections.
Method Description
addAll() It is used to adds all of the specified elements to the specified collection.
list() It is used to get an arraylist containing the elements returned by the specified
enumeration in the order in which they are returned by the enumeration.
max() It is used to get the maximum value of the given collection, according to the natural
ordering of its elements.
min() It is used to get the minimum value of the given collection, according to the natural
ordering of its elements.
copy() It is used to copy all the elements from one list into another list.
sort() It is used to sort the elements presents in the specified list of collection in ascending
order.
117
Comparable vs Comparator
Comparable Comparator
118
Lab 11
Write Java programs to:
3. Add books to a List and then, read the list of books using ListIterator, in both
backward and forward directions.
119
Set Interface
● Set is a collection that contains no
duplicate elements.
120
HashSet
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable
➔ Allows null values but if you insert more than one null values,
it would still return only one null value.
➔ Non synchronized.
121
LinkedHashSet
public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable,
Serializable
● Non synchronized.
122
TreeSet
public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable,
Serializable
● Non synchronized.
123
Lab 12
Write Java programs to:
124
Map Interface
Map
SortedMap
LinkedHashMap TreeMap
125
Map Interface
Unlike List and Set, Map does not implement Collection interface.
A map is useful if you have to search, update or delete elements on the basis of a key.
There are two interfaces for implementing Map in java: Map and SortedMap, and
three classes: HashMap, LinkedHashMap, and TreeMap.
126
HashTable
public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable,
Serializable
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
Java Hashtable implements a hash table, which maps keys to values. Uses hashing technique.
Hashing is the process of converting an object into an integer value. The integer value helps in
indexing and faster searches.
A Hashtable is an array of a list. Each list is known as a bucket. The position of the bucket is
identified by calling the hashcode() method.
127
HashMap
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable,
Serializable
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
129
TreeMap
public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>,
Cloneable, Serializable
K: It is the type of keys maintained by this map.
V: It is the type of mapped values.
130
HashMap vs HashTable
HashMap Hashtable
131
Lab 13
Write Java programs to:
132
Assignment 3
Write java programs to :
2. Reverse an Arraylist.