Java Notes
Java Notes
What is java?
- Java is high level and object-oriented programming language. Developed by james
gosling at sun microsystem , created in 1995 and JDK 1.0 was released on January 23,
1996.
- It is used to develop web application, android app, Database connection, game
development and desktop based application.
- Features
1. simple and easy to learn
2. platform independent
3. object-oriented
4. robust
5. secure
6. portable
7. multi-threaded
8. distributed
9. interpreted
- J2SE(java to standard edition)→ JSE(java standard edition)
- Initially owned and maintained by sun microsystem and now it owned and maintained by
oracle software foundation.
Class
- class is a keyword in java.
- It is used to declare class.
- it comes from word classification
- class is a blueprint of an object where we define properties or behavior and data members
of an object.
- one class have multiple objects.
Object
- Its real time entity.
- Object is a instance of class having instance variable
- new is a keyword in a java which allocates memory
- State→State represents data of an object
- Behavior→methods represents behavior of an object
- Identity→unique value.
1
JDK
- jdk stands for java development kit.
- It internally contains JRE(Java runtime environment), JVM (java virtual machine)and it
also contains classes, interface and software components like compiler(javac) which will
helps to execute or run java application/program
JRE
- jre stands for java run time environment. Its internally contains JVM (java virtual
machine)its provider environment where actually piece of code executes.
JVM
- jvm java virtual machine. Its software component in the form interpreter, which executes
byte code into native os(output).
- JVM is highly dependent on platform.
Data Type
1. primitive data type
-belongs to keywords like int, float, char, boolean, long, double, short, byte
2. non-primitive data type
-belongs to classes like String
Access Modifiers/Specifiers
- Access modifiers are keywords which define the accessibility of a class and its members.
a. Public
b. Protected
c. Private
d. Default
Setter
- Setter method takes parameter as input and initialize it value into attribute.
- Setter method is also known as mutator method
Getter
- Setter method returns the attribute value.
- Getter method is also known as accessor method
2
Constructor
- Constructor is a special type of method
- It used to initialize the object
- constructor method has same name as its class name.
- No need to call constructor method, It invoked implicitly(Automatically) just after object
creation.
- constructor method does not have any return type.
- constructor method can be overload
- Types of constructor
1. default(non-parameterized) constructor
2. parameterized constructor
- note: every class has hidden default constructor.
Polymorphism
- It’s a oop concept/pillar
- its combination of two greek words
- ploy→many
- morphic→forms
- If the single thing exists in many forms, then its known as Polymorphism.
- there two ways to achieve polymorphism
1. Method Overloading
-In single class there are multiple methods with same name but different method
signature is known method overloading.
-Method overloading is also known as static binding/early polymorphism/compile
time polymorphism, because method call is resolved at compile time.
-Ways to change method signature
a. by changing data type of parameters
b. by changing number of parameters
c. by changing sequence of parameters
2. Method Overriding
This In Java
- this is a keyword in java
- its points towards current object of class
- it used to remove shadow of attributes(shadowing off)
- It used to achieve constructor chaining.
3
Static In Java
- static is a keyword in java
- It used to declare static variable, static method and static block
static variable→
- If the variable is declared by static keyword, known as static variable. The attributes
which are more specific to class rather than specific object/instance must be declared as
static variable.
- static variables copy created per class
Static method →
- If the method is declared by static keyword, known as static method.static belongs to
class rather than specific object. single copy exists in memory.
- There is no need to create object to access static method of class. we can directly access
static method of any class by specifying class name only
- note:static method contains/access only static data members/methods
Static block→
- If block is declared by static keyword is known as static block.
- its arbitrary block of code
- it invoked automatically(implicitly) before the main method at the time class loading.
- it used to initialize static data members, setup configuration.
toString method
- toString method is built-in method of Object class
- it used to represent object/instance state in string format.
4
Array
- Arrays are objects in java
- Array is the first class object in java, because we can create object of array with or
without using new keyword, hence its known as first class object.
- It has length member which used to find size of an array.
- array reference is created in the stack and actual elements is stored in the heap.
Var-arg
- var-arg means variable arguments
- It used to declare parameter which capable to receive 0 to n number of arguments.
- var-arg type variable is declared by ellipses operator(... operator)
Containment
- Its mechanism where one class contains object of another class as an attribute or data
members, is known as the containment.
- It represents Has-A of relationship
- It used for code reusability.
- Composition→tight coupling
- Aggregation→loose coupling
5
Inheritance
- Its oop concept/pillar
- its process where one class extends/inherit/extracts the properties(fields, methods) of
another class , is known as the inheritance.
- it represents IS-A of relationship
- The extends keyword extends a class (indicates that a class is inherited from another
class)
- it used for code reusability.
- It also used to achieve run-time polymorphism(method overriding)
- types of Inheritance
1. single level
2. multi-level
3. multiple
4. hierarchical
5. hybrid
- Question: Is the java pure object oriented programming language?→No
- Because java does not support multiple inheritance through classes, but we can achieve
the functionality of multiple Inheritance through interface.
Super In Java
- super is a keyword in java
- it represents super/parent class in its child/sub class
- Used to access data members, methods and constructor of super class inside the child
class.
- every constructor have hidden field super
Package
- A java package is a group of similar types of classes, interfaces and sub-packages.
- Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
Protected Keyword
- protected is a keyword and it used as access modifier
- protected properties of class can directly accessed within the same package where its
declared. Can’t accessed outside package directly.
- but we can access protected properties of class outside the package indirectly using
inheritance(super).
6
Private Keyword
- private is a keyword and it used as access modifier
- private properties of class can be only accessed within class where its declared.
Method overriding
- If the subclass(child class) has same method as its (super class)parent class,then its
known as method overriding
- Method overriding is also known as run-time polymorphism/dynamic binding/late
binding because method class resolved at run-time.
Encapsulation
- It is oop concept/pillar.
- Encapsulation is noting, but the data hiding.
- Its stop direct access.
- Its allows indirect access →using setters and getters
Final In Java
- Final is keyword in java.
- used to declare final variable, final method and final class
1. final variable→
- If variable is declared by final keyword, known as final variable.
- Used to declare constant(unchangeable value) variable→to stop modification
- final variable must be initialized
2. final method→
- If method is declared by final keyword, known as final method.
- used to stop method overriding
- final method can’t be override
3. final class→
- If class is declared by final keyword, known as final class.
- To stop inheritance
- If you make any class as final, you cannot extend it.
7
Object class
- Object class is a built-in class, and its available in java.lang package
- Its super(parent) class of all java classes.
- All java classes implicitly(Automatically) extends Object class.
- Object class reference variable is capable to hold all type of data(objects).
Concrete class
- If the particular class defines/describes the functionality of an object, Then it known as
concrete class.
- concrete class can be instantiated(object creation)
Abstract
- abstract is a keyword
- Used to declare abstract class and abstract method.
1. abstract class→
- If the class is declared by abstract keyword is known as abstract class.
- abstract class can have both abstract and non-abstract method.
- abstract class can’t beinstantiate(we not create object)
- abstract class can have constructors and static methods also.
- It can have final methods which will force the subclass not to change the body of the
method.
2. abstract method→
- the method without method body or implementation is known as abstract method and it
declared by abstract keyword
- implementation of abstract method is left over to the inheriting sub class
- Uses
- used to achieve standardization(0 to 100%)
- used to achieve abstraction →hiding implementation and showing functionality.
8
Interface
- interface is a keyword in java and used to declare interface.
- interface is a contract between provider and consumers.
- interface can have only abstract method.
- interface can’t be instantiate(we can’t create object)
- by default all method are abstract (no need to specify abstract)
- by default all data members of interface are public, static and final.
- implementation of abstract method is left over to the inheriting sub class
- Uses→
- used to achieve standardization(100%)
- used to achieve abstraction
- used to achieve multiple inheritance
1. default method→
- default method introduced in java 8
- default is a keyword in java, it used to provide default body to the interface method.
- default method can be override
2. static method →
- static keyword is also used to provide body to the interface method
- static method can’t be override
- Question→can we write main inside the interface?→Yes, because interface can contain
static method and main method is static method.
Tagging Interface
- tagging interface is also known as marking interface.
- tagging interface does not contain anything
- its empty interface
- e.g. Cloneable interface, serializable interface are tagging interfaces
- need of marker/tagging interface→
- tagging or marking interface are only used for tagging or marking purpose, so it will give
some extra information about the class
9
Object Cloning
- object cloning means creation of exact copy of particular object is known as
objectcloning
- way to perform object cloning
1. Shallow cloning→
- Done by using assignment operator(=)
- If some changes are performed on original object it also reflects on copy
2. Deep cloning→
- Done by using Object class clone() method
- If some changes are performed on original object it does not reflects on copy
Object casting
- object casting is type casting of one object type to another object type.
- types
1. Up-casting→
- Up-casting refers to the assigning sub class object to super class reference variable
- It done automatically (implicitly)
-
2. Down casting→
- Down-casting refers to assigning superclass object to its subclass referencevariable.
- Down-casting done explicitly
- Wild card character(*) used to import all classes of particular package and it only imports
classes within the package only, it can’t import classes of sub package
- e.g.import java.util.*;
10
Java Source Structure
1. packageoptional
2. import statement(0-n)optional
3. definition of classes and interfaces(N number of classes in any order)
static import
- Static import is a feature of java programming language.
- It was introduced in java 5.0 version.
- It used to access static properties(fields, methods) of class or interface without specifying
name of class in which they declared. (without qualifying them).
- It possible statically import only public static properties.
Inner class
- Inner class is a class defined within another class.
- It can be treated as a member of outer class.
- Inner class is also known as nested class
11
Functional Interface
- Its features of java programming language, introduced in java 8.0 version.
- Functional interface is a type interface but it contains only single abstract method and 0
to N number of default and static method.
- Functional interface is also known as SAM(single abstract method).
- e.g. runnable interface, comparable interface, comparator interface
Lambda Expression
- Lambda expression is the new feature of java programming
- Introduced in java 8.0 version
- It used to implement functional interface
- Bulkiness of subclass and anonymous inner class can be reduced by writing lambda
expression.
- Benefits
1. code becomes concise
2. code becomes compact
3. code becomes readable/expressive
- syntax
()→{}
() argument list
→arrow operator
{} body
- Note-
- If the lambda expression body contain single statement then no need use curly brackets
- No need to specify data-type of arguments(we can omit data type) because compiler
automatically recognize.
String
- String is a built-in class(its non-primitive data type)
- Its available in java.lang package
- Used to represent string type of data.
- String class is immutable(modification not allowed)
- String is a first class object in java
- Two way to declare string using String class
1. Literals
- e.g. String s = "seed info";
2. new keyword
- e.g. String s1 = new String("HELLO WORLD");
12
StringBuffer
- StringBuffer is built-in class
- Its available in java.lang package
- It also used to declare string
- StringBuffer class generates mutable string (modifications allowed)
- StringBuffer is Thread-safe means synchronized
- It was introduced in first version of java
- StringBuffer dynamically grow as characters added
StringBuilder
- StringBuilder is built-in class.
- its available in java.lang package.
- its also used to declare string.
- StringBuilder class is also generate mutable string(modification allowed)
- StringBuilder is non-Thread-Safe, means non synchronized.
- it was introduced java 5.0 version
- all methods of StringBuilder is same as StringBUffer
- its faster in execution as compare StringBuffer
Optional Class
- its built-in class
- its available in java.util package
- It is feature of java programming language, introduced in java 8.0 version
- Itused to deal with NullPointerException.
- it provides methods which are used to check presence of data in particular variable.
Wrapper Class
- Java provider eight primitive data types, but sometime need to convert primitive into
object(non-primitive).
- All primitive data types have counterpart known wrapper class
1. int →Integer
2. float→Float
3. char→Character
4. short→Short
5. byte→Byte
13
6. double→Double
7. long→Long
8. Boolean→Boolean
- Wrapper classes are final
- Wrapper classes are built-in classes, available in java.lang package used to convert
primitive data types into non-primitive data type
- auto boxing is feature introduced in java 5.0 version
Exception handling
Exception→
- exception is a type of error but its recoverable and occurs at runtime of program is known
as exception.
Exception Handling→
- exception handling is powerful mechanism used to handle error/exceptions occurs during
execution of program, so that the normal flow of program can be maintained.
Normal termination →
- If program starts its execution from first line of main method and successfully terminates,
reaching at last of main method.
Abnormal termination→
- if program starts its execution from first line main of method and unexpectedly
terminates before reaching at last of main method.
- Types of exceptions
1. Checked Exception
- The exception which are occurs due problem with resource or system is known as
checked exception.
14
- The checked exception occurs during java source code converts into byte code(during
compilation) and its checked by compiler hence it also known as compile time exception.
- Checked exception must to handle
- e.g. FileNotFoundException, ClassNotFoundException
2. Unchecked Exception
- The exception which are occurs due to programmer mistake or wrong input is known as
the unchecked exception.
- The unchecked exception occurs during execution of program, hence its also known as
Run-Time exception
- unchecked exception not mandatory to handle.
- E.g. ArithmeticException, NullPointerException
- Hierarchy Of Exception
1. Throwable class
a. Exception class
i. RunTimeException
- ArithmeticException
- NullPointerException
- IndexOutOfExceptionClass
a. StringIndexOutOfExceptionClass
b. ArrayIndexOutOfExceptionClass
- InputMisMatchException
- ClassCastException
ii. IOException
- FileNotFoundException
- SecurityException
- classNotFoundException
b. Error class
Exception class
- Its Base(super) class of all exception type classes in java
- String getMesage() →its returns summary information/nature about the error.
- Void printStackTrace()→from where error is occurred
Try
- try is keyword in java and it used in exception handling.
- try is a block contains exceptional/risky code that might be generate exception.
15
Catch
- catch is keyword in java and it used in exception handling.
- It handles the exception that occurred in its try block.
- It has one exception type parameter which receives exception object.
- It executes only if the exception is occurred in try block.
Finally
- finally is keyword in java and its used in exception handling.
- finally block executes always regardless whether the exception thrown or not
- it used to write the code that executes always.
- finally block is optional block
- it used to avoid resource leakage.
Multiple catch
- Individual error handling done by multiple catch.
- As we know that multiple exceptions occurs in try block.
- Error message should be different for particular exception.
- Multiple catch block used to handle multiple exception, so its enables to display custom
error message.
- Only matching block is executed
- Among all specific exception handlers →all exception handler must be last one.
Throw
- throw keyword in java
- used to throw exception from called method to the caller method. It used to throw only
single exception and its must be unchecked exception.
Throws
- throws is keyword in java.
- used to declare one or more (multiple) exception in called method
- it used to declare both checked and unchecked
- throws is the part method signature.
16
Reflection
- Reflection is a powerful technique or mechanism used to fetch and examine metadata of
class
MetaData→
- metadata is nothing but the data about data is known as metadata and it gives some extra
information about the data.
Class→
- Its built-in class
- Available in java.lang package.
- Class class is a part of java reflection api
- It represents single class or interface
forName()→
- It is a Class class method used to load the class dynamically at runtimeand it takes one
fully qualified name of class as an argument that we want to load.
Collection Framework
- In java Collection is a framework used to store and manipulate group of objects.
- Its collection of classes and interfaces.
- Limitation of Array
1. As we know that Arrays are fixed in size
2. can holds only homogeneous data
3. does not provide any built-in manipulation method
- Benefits Of Collection
1. Not fixed in size because its grow dynamically
2. Provides readymade architecture
3. It has built-in data structure and algorithm
a. so need not to write code
17
b. its highly efficient
4. can holds both homogeneous and heterogeneous objects
2.Map Interface
A. HashMap class
B. HashTable class
i. properties class
C. SortedMap interface
i. NavigableMap interface
a. TreeMap class.
List interface→
- It provides indexing
- Allows duplicates
- Ordered
- List implementing classes
1. ArrayList
- It list implementing class
- Non synchronized means non thread safe.
- Its suitable for sorting purpose
- It not suitable for manipulation purpose
- contiguous memory location
2. LinkedList
- It list implementing class
- Non synchronized
18
- Its suitable for manipulation purpose
- It does not allocate memory in contiguous location.
- linkedList is known doubly list
3. Vector
- It list implementing class
- Synchronized means thread safe
- Note - As we know ArrayList, LinkedList, Vector are general purpose collection
4. Stack
- Its a subclass of Vector class
- Synchronized means thread-safe
- It not general purpose collection
- Its Data Structure and its works on approach FILO(first in last out)
Set interface→
- Unique collection
- Unordered
- Does not provide indexing
- Set implementing classes
1. HashSet
- Its Set implementing class
- Non synchronized
- Contains only unique objects
- may contain null
- It unordered and unsorted
2. SortedSet interface
- Its Set implementing interface
- Unordered and sorted to its natural ordering
- Its generally used for sorting purpose
- Implemented by TreeSet class
a. NavigableSet interface
-Its also SortedSet
-It used for searching purpose
-It can be accessed in both ascending and descending order
-Implemented by TreeSet class
b. TreeSet class
- Its SortedSet implementing class
19
- It contains unique objects
- Its unordered and sorted
- It can’t contains null
Queue interface→
- Its work on approach i.e. FIFO(first in first out)
- Implemented by LinkedList and PriorityQueue
Map interface→
- Map interface is associates with keys and values.
- Each key a value pair is known as an entry.
- Map can’t contain duplicate key.
- key and value can be any java class and interface type
- Implementing classes HashMap, HashTable
- Map Implementing Classes
1. HashMap class
- Its map implementing class
- Contains key and value pair.
- It allows one null key and multiple null value
- Its unsorted and unordered
- Non synchronized means non thread safe
2. HashTable class
- It map implementing class
- Contains key and value pair.
- It does not allow null key and null value
- Its unsorted and unordered
- Synchronized means thread safe
3. SortedMap interface
- Its map implementing interface
- It used for sorting purpose
- Its unordered and sorted to its natural order of its keys
- Implemented by TreeMap class.
a. NavigableMap interface
- Its SortedMap implementing interface
- Contains key and value pair.
- It used for searching purpose
- Its unordered and sorted to its natural order of its keys
20
- Implemented by TreeMap class.
- Iterator interface→
- Iterator interface allows to visit elements in the container(collection)one by one
Generic class
- As we know that many algorithms are logically same irrespective of data to which they
are applied
- Generic class useful to define algorithm once, independent of data
- Solution : write generic class
- Ways to write class
1. Using Object class→before java 5.0
- It not type safe, require explicit type casting
2. Using type-parameter(placeholder) → after java 5.0
- Its type safe, does not require explicit type casting
1.Comparable
- It has single abstract method compareTo(T ob) and return integer value.
- comparable used to compare on the basis of only single attribute.
2.Comparator
- It has single abstract method compare(T ob1, T ob2) and return integer value
- Comparator used to compare on the basis of multiple attributes.
Properties Class
- Its map implementing class and its subclass of HashTable class
- It is also known as utility class that allows you to store and retrieve configuration
properties of application like database in a key-value format.
21
Stream Api
- The stream api in java is a functional programming approach used to process sequenced
object like array, collection in pipeline manner.
- It provides readymade, concise and expressive way to perform operations on data stream
- benefits→
1.Declarative -specify what you want to do, not how to do.
2.Auto-iterable -no need of loops to iterate
3.Lazy-operation are only executes when needed
Method reference
- Its new feature java 8.0
- It used to provide existing method body to the functional interface method
- Method reference can be given to
1. static method
2. instance method
3. constructor method
- using method reference operator::
22
File Io
- Stream--it a flow of byte
Input Stream→
- Its flow of bytes from data destination(SSD/hard Disk) to the program memory, is known
as Input Stream.
- It used to perform read operation only.
Output Stream→
- Its flow of bytes from program memory to the data destination(SSD/hard Disk),is known
as Output Stream.
- It used to perform write operation.
File class
- Its built-in class available in java.io package
- File class represents(abstract representation of file) the file.
- It used to access information about the file.
- File class object does not provide any file processing functionality.
FileInputStream
- It used to open the file in read mode only.
- Its throws FileNotFoundException if file doesn’t exists.
- It has method int read() its returns next byte of data and terminates reading if end of
stream is reached
- End of stream is indicated by -1
FileOutputStream
- It used to open the file in write or append mode
- Its creates file, if file does not exists
- It has write(byte b) method to write next byte of data
Serialization
- Serialization is a persistence mechanism.
- Persistence→ It a technique used to store object state beyond the scope jvm permanently.
- Reason : for future reuse.
24