You are on page 1of 60

Java Basics- Strings, Data

structures & Generics

Sanal Varghese
1. Java - Strings
String
▷ String is a sequence of characters.
▷ In Java, string is an object that represents a
sequence of characters
▷ Not NULL terminated.
▷ String – Object or Primitive?
• String is not a primitive data type.it is an object
type.
▷ String objects are immutable!
• once a string object is created it cannot be
altered.
DECLARING & INITIALISING
Two ways to create String object:

▷ Using new Keyword


String name= new String("Craig");

▷ By string literal
String name = "Craig";
Important operations of strings

▷ String Concatenation
▷ String Comparison
▷ Substring
▷ Length of String etc.
String concatenation
▷ String concatenation forms a new string that is the
combination of multiple strings

1. By ‘+’ (string concatenation) operator


class TestStringConcatenation1{
public static void main(String args[]){
String s="Hello"+" World";
System.out.println(s);//Hello World
}
}
String concatenation contd
2. By concat() method

class TestStringConcatenation3{
public static void main(String args[]){
String s1="Hello";
String s2="World";
String s3=s1.concat(s2);
System.out.println(s3);//Hello World
}
}
String Comparison
▷ String can be compared using

1. By equals() method
2. By = = operator
3. By compareTo() method
By equals() method
▷ compares the original content of the string.
▷ returns true if contents are equal.
▷ case sensitive.

public static void main(String []args){


String s1 = "hello";
String s2 = "hello";
String s3 = new String ("Hello");

System.out.println(s1.equals(s2)); \\ true
System.out.println(s2.equals(s3)); \\false
System.out.println(s2.equalsIgnoreCase(s3)); true
}
▷ equalsIgnoreCase() method is not case sensitive.
Using ‘==’ operator
▷ The = = operator compares references( i.e memory location)
▷ returns true if refrences are equal.

public static void main(String []args){


String s1 = "tutorialspoint";
String s2 = "tutorialspoint";
String s3 = new String ("Tutorials Point");
System.out.println(s1 == s2); //true (because both refer to same instance)
System.out.println(s2 == s3); //false(because s3 refers to new instance)
}
compareTo() method
▷ comparing strings lexicographically(alphabetically
ordered).
▷ comparison is based on the Unicode value of each
character
▷ returns
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
SubString
▷ substring is a subset of another string.
▷ Obtain SubString from a given string using below methods
1. substring(int startIndex):
2. substring(int startIndex, int endIndex): //endIndex: exclusive

public static void main(String args[]) {

String str= new String("quick brown fox jumps over the lazy dog");
System.out.println(str.substring(15)); // jumps over the lazy dog
System.out.println(str.substring(15, 20)); // jump
}
Methods of String Class
▷ contains():- returns true if sequence of char values are found in
this string otherwise returns false.
▷ length() : method finds the length of the string.
▷ indexOf() :-returns index of given character value or substring.
▷ replace() :-returns a string replacing all the old char or
CharSequence to new char
▷ getChars() :-copies the content of this string into specified char
array
▷ charAt() :-returns a char value at the given index number. The
index number starts from 0.
StringBuffer class
▷ used to created mutable (modifiable) string.
▷ thread safe & synchronized
▷ automtically increases size for additional characters.

Constructors of StringBuffer class :


StringBuffer(): creates an empty string buffer with the initial capacity of
16.
StringBuffer(String str): creates a string buffer with the specified string.
StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
Methods of StringBuffer class
▷ append(String s): used to append the specified string with this string.
▷ insert(int offset, String s): used to insert the specified string with this
string at the specified position.
▷ replace(int startIndex, int endIndex, String str): used to replace
the string from specified startIndex and endIndex.
▷ delete(int startIndex, int endIndex): used to delete the string from
specified startIndex and endIndex.
▷ reverse(): is used to reverse the string.
▷ capacity(): is used to return the current capacity.
StringBuilder class
▷ used to created mutable (modifiable) string.
▷ thread safe & synchronized
▷ automtically increases size for additional characters.

Constructors of StringBuffer class :


StringBuffer(): creates an empty string buffer with the initial capacity of
16.
StringBuffer(String str): creates a string buffer with the specified string.
StringBuffer(int capacity): creates an empty string buffer with the
specified capacity as length.
Comparison

String StringBuffer StringBuilder

• Immutable • mutable • mutable


• Slow & Consumes • fast & consumes • faster & consumes lower
memory. comparatively low memory . memory comparatively.
• thread-safe • thread safe. • Not thread-safe
• less efficient. • less efficient • more efficient
toString() Method in Java
▷ used to get string representation of an object.

Default Behavior
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}

Overriding Default Behavior


@Override
public String toString() {
return "Customer [balance=" + balance + ", getFirstName()=" + getFirstName()
+ ", getLastName()=" + getLastName() + "]";
}
2. Data Structures
Data Structures
▷ way to store and organize data so that it can be
used efficiently.
▷ Types of data structures.

• Array
• Linked List
• Hash Map
• Set
• Stack
• Queue
Hierarchy of data structure java
Array
▷ collection of items stored at contiguous memory
locations.
▷ an array in Java is bounded.
▷ Array in Java are also homogeneous.
Advantages & Disadvantages
▷ Advantages of Array
• Array provides the single name for the group of variables of the
same type.
• Traversing an array is a very simple process.
• Any element in the array can be directly accessed by using the
index.

▷ DisAdvantages of Array
• The size of array must be known in advance .
• It is almost impossible to expand the size of the array at run
time.
• Elements in the array need to be contiguous.
Linked List
▷ collection of objects called nodes that are randomly stored in
the memory.
▷ A node contains two fields - data & address of next node.
▷ Single , double and circular linked list.
When to use ArrayList vs LinkedList in Java
▷ It is best to use an ArrayList when:

• You want to access random items frequently


• You only need to add or remove elements at the end of
the list.

▷ It is best to use a LinkedList when:

• You only use the list by looping through it instead of accessing


random items
• You frequently need to add and remove items from the
beginning or middle of the list
HashMap
▷ Map based collection class that is used for storing Key & value
pairs.
▷ contains only unique keys.
▷ non synchronized.
▷ Allows to store NULL elements

Constructors of Java HashMap


▷ HashMap() : It is used to construct a default HashMap.
▷ HashMap(Map<? extends K,? extends V> m) : used to initialize the
hash map by using the elements of the given Map object m.
▷ HashMap(int capacity) : Initializes the capacity of the hash map to the
given integer value.
Methods of Java HashMap class
▷ V put(Object key, Object value) : used to insert an entry in
the map.
▷ boolean remove(Object key, Object value) : removes the
specified values with the associated specified keys from map.
▷ boolean containsValue(Object value) : This method returns
true if some value equal to the value exists within the map,
else return false.
▷ void putAll(Map map) : used to insert the specified map in
the map.
Hashset
▷ collection of items where every item is unique.
▷ Insertion order is not maintained.
▷ dosen’t allow duplicates.
▷ Non-synchronized.
▷ The iterator returned by this class is fail-fast.
▷ HashSet stores the elements by using a mechanism called
hashing.
Methods of Java HashSet class
▷ add(E e) : used to add the specified element to this set if it
is not already present.
▷ clear() : It is used to remove all of the elements from the
set.
▷ clone() : used to return a shallow copy of this HashSet
instance:
▷ remove(Object o) : used to remove the specified element
from this set if it is present.
▷ Size() : It is used to return the number of elements in the set.
Stack
▷ Stack is an ordered list in which, insertion and
deletion can be performed only at one end.
▷ Based on LIFO
Stack Initialization.
Stack Class Constructor
public Stack()

• default constructor.
• creates empty stack.

Creating a Stack
Stack stk = new Stack();
or
Stack<type> stk = new Stack<>();
Stack Operations
▷ Push : Adds an item in the stack
▷ Pop : Removes an item from the stack.
▷ Peek or Top: Returns top element of stack.
▷ isEmpty: Returns true if stack is empty, else false.
▷ search(Object o) : The method searches the
specified object and returns the position of the
object.
illustration of stack operations
Applications of Stack

▷ Browser
▷ Function Call
▷ String Reversal​
▷ Memory management
▷ Syntax Parsing
• compilers use a stack for parsing the syntax of
expressions
Queue
• linear structure which follows a particular order in which
the operations are performed.
• Follows FIFO
• Insertion & deletion at different ends.
Operations on Queue:
▷ add(object) : used to insert the specified element into
this queue and return true upon success.

▷ remove(): used to retrieves and removes the head of this


queue.
▷ poll(): used to retrieves and removes the head of this
queue, or returns null if this queue is empty.
▷ peek(): retrieves, but does not remove, the head of this
queue, or returns null if this queue is empty.
Applications of Queue

▷ Queues are widely used as waiting lists for a single


shared resource like printer, disk, CPU.
▷ Queue are used to maintain the play list in media players
in order to add and remove the songs from the play-list.
▷ Queues are used in operating systems for handling
interrupts.
3.Generics
Generics
▷ generics enable types (classes and interfaces) to be
parameters when defining classes, interfaces and methods.
▷ We use angle brackets (<>) to specify the type parameter.
▷ Stronger type checks at compile time.
▷ Elimination of casts.
▷ Enabling programmers to implement generic algorithms.
Why Use Generics?
Generic Types
• A generic type is a generic class or interface that is parameterized over
types
• type parameter section, delimited by angle brackets (<>), follows the
class name.

Type Parameter Naming Conventions


• E - Element (used extensively by the Java Collections Framework)
• K - Key
• N - Number
• T - Type
• V - Value
Invoking and Instantiating a Generic Type
• Invocation
Box<Integer> integerBox;

• Instantiation
Box<Integer> integerBox = new Box<Integer>();

• The Diamond
Replacing the constructor of a generic class with empty set of
arguments.
Box<Integer> integerBox = new Box<>()
Multiple Type Parameters
• Generic class can have multiple type parameters.
public class <class name><K, V>
• you can also substitute a type parameter (i.e., K or V) with a
parameterized type (i.e., List<String>).
p = new OrderedPair<>("primes", new Box<Integer>(...));

Raw Types
• Used to get Pre-Generic behaviour.
Generic Methods
▷ we don’t want the whole class to be parameterized.
▷ parameter's scope is limited to the method where it is declared.
▷ Static and non-static generic methods are allowed.
▷ Syntax
▷ All generic method declarations have a type parameter section
delimited by angle brackets (< and >) that precedes the method's
return type
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2)
Advantages of Generics

▷ Types safety.
▷ Typecasting is not required
4. Exceptions & Handling in
Java
Exceptions and Errors
▷ an eventwhich occurs during the execution of a program, that
disrupts the normal flow.
▷ Exception handling gives us another opportunity to recover from
the abnormality.

Kinds of Exception
• Checked exception
• Error
• Runtime exception
Checked Vs Un-Checked Exceptions
Checked Exceptions
• Checked at compile-time.
• Example : FileNotFoundException,
ClassNotFoundException.

UnChecked Exceptions
• Checked at Runtime.
• Mostly programming bugs/bad data provided by
programmer.
• Example: NullPointer, SecurityException etc..
Handling Exceptions
▷ Mechanism to handle runtime errors.
▷ Helps to maintain the normal flow of the application.
▷ In Java it is handled using 5 keywords

• try – A block of source code that is to be monitored for exception


• catch – It handles the specific type of exception along with the try
block.
• throw – It is used to throw specific exception from the program code.
• throws – It specifies the exception that can be thrown by a particular
method.
• finally – it specifies the code that must be executed even though
exception may or may not be occur
The try-catch Block
▷ Used to enclose code that could throws exception

try {
code
}
catch (ExceptionType name) {

}
▷ A try block must be followed by catch blocks or finally block or
both.
▷ A catch block is where you handle the exceptions.
▷ Can have several catch blocks associated with it.
▷ Place generic exception handler at the last.
Java Nested try block
▷ To handle situations where a block may cause one error and the entire block
itself may cause another error.
try {
statement 1;
statement 2;
try {
statement 1;
statement 2;
} catch (Exception e) {
}
} catch (Exception e) {
}

▷ Child catch blocks are not handling any exception, the jumps to the parent
catch blocks.
The finally Block
▷ Always executes when the try block exits.
▷ allows the programmer to avoid having cleanup code
accidentally bypassed by a return, continue, or break.
▷ finally block is a key tool for preventing resource leaks.
▷ Finally block is optional.

Cases when the finally block doesn’t execute


• The circumstances that prevent execution of the code in a
finally block are:
• – The death of a Thread
• – Using of the System. exit() method.
• – Due to an exception arising in the finally block.
Throw keyword
▷ used to explicitly throw an exception from a method or any block of
code.
▷ throw keyword is mainly used to throw custom exceptions.
▷ flow of execution of the program stops immediately after the throw
statement is executed.
▷ Instance must be of type Throwable or a subclass of Throwable
Syntax
throw Instance

Example:
throw new ArithmeticException("/ by zero");
throws Keyword
▷ used to indicate method might throw one of the listed
exceptions.
▷ throws keyword to delegate the responsibility of exception
handling to the caller.

Synatx
type method_name(parameters) throws exception_list
throws Keyword contd...
class ThrowsExecp
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
}
}
}
Custom Exception in Java
▷ User-defined exceptions.
▷ To catch and provide specific treatment to a subset of existing
Java exceptions
▷ For handling Exceptions that are specific to the business logic
and workflow.
▷ can be both Checked or Unchecked exceptions.
Exception Handling – Best Practices
▷ Use Specific Exceptions -always throw and catch specific exception
classes
▷ Throw Early or Fail-Fast - catch exception only when we can handle it
appropriately
▷ Closing Resources - Should close all the resources in finally block or
use Java 7 try-with-resources.
▷ Logging Exceptions - Empty catch blocks are bad way writong code.
▷ Using Custom Exceptions - Can provide more details to error.
▷ Document the Exceptions Thrown - Use javadoc @throws to clearly
specify the exceptions thrown by the method.
Thanks!
Any questions?

You might also like