Professional Documents
Culture Documents
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:
▷ 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
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.
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.
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.
Default Behavior
public String toString() {
return getClass().getName()+"@"+Integer.toHexString(hashCode());
}
• 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:
• 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.
• 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 {
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.
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?