Escolar Documentos
Profissional Documentos
Cultura Documentos
2. OOPS Fundamentals.
A class is an entity that determines how an object will behave and what the object will contain. In other
words, it is a blueprint or a set of instructions to build a specific type of object.
An object is nothing but a self-contained component which consists of methods and properties to make a
particular type of data useful. Object determines the behavior of the class.
4. Naming Conventions
Naming Convention is a set of rules for choosing the character sequence to be used for identifiers which
denote variables, types, functions, and other entities in source code and documentation.
5. Encapsulation
Encapsulation is a mechanism of wrapping the variables and methods together as a single unit. In
encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through
the methods of their current class. Therefore, it is also known as data binding.
To achieve encapsulation-
6. Constructors
A constructor is a special method that is used to initialize the newly created object and is called just after
the memory is allocated for the object.
7. Method Overloading
Method Overloading is a feature that allows a class to have more than one method having same name, if
their argument lists are different.
8. Recursion
The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function.
9. Access Modifiers
Access Modifiers helps to restrict the scope of a class, constructor, variable, method.
There are four types of access modifiers. They are
Public, Protected, Default, Private
Public: The public access modifier is specified using the keyword public. Classes, methods or data members
which are declared as public are accessible from every where in the program. There is no restriction on the
scope of a public data members.
Protected: The protected access modifier is specified using the keyword protected. The methods or data
members declared as protected are accessible within the same package or sub classes in different package.
Default: When no access modifier is specified for a class, method, or variables, -it is said to be having the
default access modifier by default.
Private: The private access modifier is specified using keyword private. The methods or data members
declared as private are accessible only within the same class in which they are declared.
Mutator method is used to control changes to a variable. They are also widely known as setter methods.
Accessor method is used to return the value of a private member variable. They are also widely known as
getter methods.
12. Inheritance
Inheritance is a mechanism in which one class allow to inherit features(fields and methods) of another
class. The keyword used for inheritance is extends.
Super class: The class whose features are inherited is known as super class(base class,parent class).
Sub class: The class that inherits the other class is known as sub class(derived class, child class, extended
class).
Reusability: Inheritance supports the concept of “reusability”, i.e when we want to create a new class and
there is already a class that includes some of the code that we want, we can derive our new class from
existing class. By doing this we are reusing the fields and methods of existing class.
13. Method Overriding
Overriding is a feature that allows a sub class to provide specific implementation of a method that is already
provided by one of its parent classes. When a method in sub class has same name, same parameters or
signature and same return type as method in super class, then the method in sub class is said to override
the method in the super class.
Method overriding is one of the way by which java achieve runtime polymorphism.
It is possible to have different return type for a overriding method in child class, but child’s return type
should be sub type of parent’s return type. Overriding method becomes variant with respect to return type.
The super keyword in java is a reference variable that is used to refer parent class objects. The keyword
super came into picture with the concept of inheritance.
It is majorly used in following contexts-
16. Polymorphism
Polymorphism is the capability of a method to do different things based on the object that it is acting upon.
In other words, polymorphism allows you define one interface and have multiple implementations.
Static Binding: The binding which can be resolved at compile time by compiler is known as static binding.
Binding of all the static, private and final methods is done at compile time. Compiler knows that all such
methods cannot be overriden.
Dynamic Binding: When compiler is not able to resolve the call/binding at compile time, such binding is
known as Dynamic binding. Overriding is perfect example of Dynamic binding. In overriding both parent and
child classes have same method.
- static variable: A static variable is a class variable and doesn’t belong to object/instance of the class.
- static method: Method that can be called without creating an object of class. Static methods are
associated with class in which they reside. Static methods cannot be overriden.
- static block: Static block is the group of statements that gets executed when the class is loaded into
memory. Static block is used to initialize the static variables of the class. We can’t access non static variables
inside a static block. Static block code is executed only once when a class is loaded into memory.
-static class: static keyword is used with nested classes. Nested static class doesn’t need reference of outer
class, but non static nested class or inner class requires outer class reference.
Inner class or non static nested class can access both static and non static members of outer class. A static
class cannot access non static members of outer class. It can access only static members of outer class.
An instance of inner class can’t be created without an instance of outer class
- static import: Normally we access static members using class reference, we can use static import to avoid
class reference.
Final: final is a non access modifier that is applicable only to a variable, a method or a class.
Final variables: when a variable is declared with final keyword, its value can’t be modified.
Final class: when a class is declared with final keyword, it is called final class. A final class cannot be
inherited.
Final method: when a method is declared with final keyword, it is called final method. A final method
cannot be overriden.
Initializer block: Initializer block contains the code that is always executed whenever an instance is created.
Initializer block is always executed before constructor. It is used to declare/initialize the common part of
various constructors of class.
Static block: static block is used to initialize the static variables. This block gets executed when class is
loaded into memory. A class can have more than one static blocks, which will execute in the same order in
which they are written in program.
An abstract class is a class that is declared abstract-it may or may not include abstract methods. Abstract
classes can’t be instantiated, but they can be sub classed. An abstract class may have static fields and static
methods. When an abstract class is subclassed, the subclass usually provides the implementation for all of
the abstract methods in its parent class. However, if does not, then the subclass must also be declared
abstract.
21. Interfaces
An interface is just the declaration of methods of an object, its not the implementation.
In interface, we define what kind of operation an object can perform. These operations are defined by the
classes that implement interface.
- You expect that unrelated classes would implement your interface. For example, the interfaces
Comparable and cloneable are implemented by many unrelated classes.
- You want to specify the behavior of a particular data type, but not concerned about who implements its
behavior.
- You want to take advatage of multiple inheritances.
Shallow cloning: The default version of clone() method creates the shallow copy of an object. The shallow
copy of an object will have exact copy of all the fields of original object. If original object has any references
to other objects as fields, then only references of those objects are copied into clone object, copy of those
objects are not created. That means any changes made to those objects through clone object will be
reflected in original object or vice-versa. Shallow copy is not 100% disjoint from original object. Shallow
copy is not 100% independent of original object.
Deep cloning: Deep copy of an object will have exact copy of all the fields of original object jsut like shallow
copy. But in additional, if object has any references to other objects as fields, then copy of those objects are
also created by calling clone() method on them. That means clone object and and original object will be
100% disjoint. They will be 100% independent of each other
strictfp is a keyword used for restricting floating point calculations and ensuring same result on every
platform while performing operations in the floating point variable.
Strictfp modifier is used with classes, interfaces and methods only. When a class/interface is declared with
strictfp modifier, then all methods declared in class/interface and all nested types declared in the class are
implicitly strictfp.
Type of relationship always makes to understand how to reuse the feature from one class to another class.
In java programming we have three types of relationship. They are
Is-A Relationship
Has-A Relationship
Uses-A Relationship
Is-A Relationship: In Is-A Relationship one class is obtaining the features of another class by using
inheritance concepts with extends keywords
Has-A Relationship: In Has-A Relationship an object of one class is created as data member in another class
the relationship between these two classes is Has-A
Uses-A Relationship: A method of one class is using an object of another class the relationship between
these two classes is Uses-A relationship.
25. Immutable object: An object whose state cannot be changed after it is cerated is called an immutable
object
26. Immutable class: A class whose objects are immutable is called immutable class
27. Java Heap space: Java Heap space is used by java runtime to allocate memory to objects and JRE classes.
Whenever we create any object, its always created in Heap space
Garbage Collection runs on heap memory to free the memory used by objects that doesn’t have any
reference. Any object created in heap space has global access and can be referenced from anywhere of
application.
28. Java Stack Memory: Java stack memory is used for execution of thread. They contain method specific
values that are short lived and references to other objects in the heap that are getting referred from the
method.
29: Garabge Collection: The process of removing unused objects from heap memory is known as Garbage
Collection and this is part of memory management.
Languages like c/c++ don’t support automatic garbage collection, however in java the garabge collection is
automatic
30. Thread: A thread of execution is the smallest sequence of programmed instructions that can be
managed independently by a scheduler.
31. javap command: The javap command disassembles one or more class files. Its output depends on the
options used. If no options are used, javap prints out the package, protected, and public fields and methods
of the classes passed to it. javap prints its output to stdout.
33. Lot of string manipulations imply lot of time and lot of memory requirements, this will degrade the
performance, so we better go for classes like StringBuffer and StringBuilder. These both classes belong to
java.lang package
34. StringBuilder is not synchronized which means it is not thread safe, whereas StringBuffer is
synchronized, i.e they are thread safe.
We don’t need thread safety always, so we can go for StringBuilder. StringBuilder is very fast and
performance than StringBuffer.
When multiple threads are acting on the same string go for StringBuffer. If there are no multiple threads
acting on the same string go for StringBuilder
35. append() of StringBuilder returns an object. replace(int start, int end, String str) of StringBuilder returns
an object. start is inclusve and end is exclusive
36. caller vs callee: If a method A calls method B, then method A is a caller and method B is known as callee.
37. Method overloading: Methods are overloaded when they have same name and different parameters.
Parameters must be different either in their data type or their count. Method cannot be overloaded based
on return type or Parameter names.
Call to overloaded method is resolved at compile time and is done based on data type and count of
arguments passed to the method.
MethodDemo5.java if add(1,2) is passed both int, double and double,int have chances this leads to
ambiguity Overloading can lead to ambiguous situation
variables, methods --> camel notation word with lower case, for two words second word starts with
uppercase for more than two words all from second word begin with upper case
Type names(class names and interface names): Hungarian notation: begin with uppercase
final/constants: completely uppercase, separate with underscore if more than one word
default constructor is not provided by compiler if there is any parameterized constructor, if class does not
have default constructor
if we provide a constructor and still do not initialize some of the instance variables then those variables are
initialized by the system to their respective values based on variable data type
Since object is created only once in a lifetime, constructors execution happen only once in lifetime of an
object
A class can have more than one constructor with different parameters. This is called constructor
overloading.
In java we dont have local level static variables, we have class level static variables
static blocks purpose is to initialize the static variables. Static variables can be accessed in static blocks
Methods which are declared in java but are not implemented in java are called native methods. Native
methods will be in the library which are platform dependent
Singleton: A class for which only one instance can exists in the entire application is known as Singleton.
Singleton is name of one of the Object oriented Design Ptterns.
instanceof keyword: Animal a=new Dog(); 1) a instanceof Dog true and 2) a instanceof Animal true
Object binding with method during runtime is called dyamic method dispatch
Inheritance and Dyanmic method dispatch together will achieve polymorphism i.e one name ,many
implementations
when we declare static, then we use less memory thereby faster access
final variables and final fields are different. If do not initialize just declare then it is final field.final fields
must be initialized at the place of declarartion or in every constructor of the class
if a class has atleast one abstract method , then the class must be declared abstract
we can declare a class as abstract even if it does not have abstract methods. This is done to prevent explicit
instantiation of the class.
An abstract class may have final method but a final class cannot have an abstract method.
Many of the java advance topics like Collections, JDBC, servlets, EJB,JMS, uses the concept of interfaces to
the core.
Interfaces cannot be instantiated. Interface need not be abstract. Interface variables can declared. These
type of variables form under category of reference variables
1. Implementation inheritance
--> class inherits from another class
--> only single inheritance
2. interface inheritance
--> class implementing interfaces
--> interface inherits from another interfaces
--> multiple inheritance is allowed in this kind of inheritance
Interfaces have no provision of instance variables, constructors or blocks, ofcourse we can declare
constants. Static final variable is effectively a constant.
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of
program’s instructions.
Exception is a critical situation which arises at runtime, naturally because of code execution.
Exception arise due to deviation from logic. Whose logic ? It could be logic of runtime or it could be
application logic where we implement our business rules
Exception can be raised either by the system when we deviate from system logic or it can be raised by us
when the code execution deviates from our application logic
Exception can be represented as an object, its an object since it is supposed to hold the state and this object
has already infromation about the problem, where is the problem and how the problem has propagated
from one method to another.
Exception thrown or raised from a method, if not handled by the method is propagated from place where
method was called, i.e to the calling method.
so java language has certain features where in we can perform the exception handling mechanism which is
avaliable with the help of through certain keywords
There are five keywords involved in exception handling: try, catch, throw, throws and finally.
Any object, which can be represented as an exception object must be a part of hierarchy where a class
called Throwable at the top.
Java.lang.Throwable class
Throwable class has two sub classes, one Exception and two Error
Infrastructure problem: runtime is out of memory, these we can’t handle, so these are represented as
errors.
Every method under execution has a memory associated with it known as stack, if stack overflows these are
represented as errors
we can have nested try catch blocks used for executing all the statements if there are three statements and
exception is raised at second statement we will handle and third one will execute by using nested try catch
blocks
exception handling code is written in catch block. There sholud not be any statements between try and
catch blocks
Resource which is opened inside try is automatically closed at the end of try, so usage of finally now is
reduced.
A try can have multiple catch blocks. This is to facilitate the feature of handling, different exceptions are
handled in different ways
A catch of supertype of exception must be at the end
1) void printStackTrace()
prints the stack trace of this exception to the standard error stream(tells us about exception propagation
path)
2) String getMessage()
returns the error message string of this throwable object(tells us about problem description)
3) String toString()
returns a short description of this throwable object
checked exceptions are instances of Exception class or one of its subclasses excluding Runtime branch
checked exceptions must be declared in the throws clause of the method throwing them
unchecked exceptions are instances of RuntimeException class or one of its subclasses. you need not
declare unchecked exceptions in throws clause of the throwing method
Collection: A collection is an object that groups multiple elements(objects) into a single unit accessed with
common reference.
There is no direct class avaliable which implements Collection interface. Collection has a sub interface List
i.e List inherits from Collection.
A List is an ordered collection(sometimes called a sequence). Lists can contain duplicate elements. The user
of a List generally has a precise control over where in the List each element is inserted. The user can access
elements by their integer index(position)
ArrayList implements List interface. ArrayList is a class.The methods in ArrayList are not synchronized.
Vector implements the List. The vector class implements a growable array of objects.
The methods in vector class are synchronized. Hence Vector is said to be thread safe
thread safe is discussed in multi threading.
Map is an interface. An implementation of Map is known as HashMap. HashMap methods are not
synchronized.
Generics: The idea is to allow type (Integer, String, … etc and user defined types) to be a parameter to
methods, classes and interfaces.
For example, classes like HashSet, ArrayList, HashMap, etc use generics very well. We can use them for any
type.
Type inference: no need to specify data type on the right hand side
No casting implies code is much faster. It is type safe, because we know what type of data or values we are
working with.
Reusability by using generics. Generic class written once and used in the context of other data types
ArrayList is heterogenous
bounded generics: generic class bounds to a specific class. For example T is replaced by T extends Number
in Stack class.
This Stack class can be instantiated only for Number or Number sub classes
Properties class in java utility package. Properties instance represents a set of name value pairs where name
and value are both of type strings
Every java runtime maintains a properties object, it has certain predefined key value pairs, keys are fixed,
values depend on platform where we are running the application
properties maintained by runtime are system properties.
This is how we can read properties file which is outside the application
reading Countries.properties file from PropertiesDemo2.java.
i.e such properties file is known as external resource. Very much useful when reading a configuration file for
an application.
Imagine our application connects to a database, so all the details required to establish connection with the
database can be specified in the external properties file, benefit is application does not bother about which
database it is using
Java Collection framework provides many interfaces (Set, List, Queue, Deque, etc.) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet, etc.).
Collections is a class
Arrays.sort works for arrays which can be of primitive data type also. Collections.sort() works for objects
Collections like ArrayList, LinkedList, etc.
Object Serialization in java: The process of representing state of the object in an ordered series of bytes is
called serialization
if one end is java and other end is not, then we go for xml format of serialization
SQL injection is placement of malicious code in SQL statements, via web page input