Java Porgramming Part 1
Java Porgramming Part 1
Java Porgramming Part 1
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.
JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime
environment in which Java bytecode can be executed. It is a specification which specifies the
working of Java Virtual Machine. Its implementation has been provided by Oracle and other
companies. Its implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform dependent).
It is a runtime instance which is created when we run the Java class. There are three notions of the
JVM: specification, implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to
provide the runtime environment.
It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that
JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. It is a software development environment which is
used to develop Java applications and applets. It physically exists. It contains JRE + development
tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
Types of Variables
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory allocation
for static variables happens only once when the class is loaded in the memory.
Java Comments
Single Line Comment:
The single-line comment is used to comment only one line of the code. It is the widely used and
easiest way of commenting the statements.
Single line comments start with two forward slashes (//). Any text in front of // is not executed by
Java.
Multi Line Comment
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use
single-line comments there).
/*
This
comment
*/
Java OOPs Concepts
Object:
An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the
objects.
Class:
Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint
from which you can create an individual object. Class doesn't consume any space
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example: to convince
the customer differently, to draw something, for example, shape, triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example, phone call,
we don't know the internal processing. In Java, we use abstract class and interface to achieve
abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the
data members are private here.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when
classes are aware of each other. If a class has the details information of another class, there is strong
coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a
class, method, and field. You can use interfaces for the weaker coupling because there is no concrete
implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single well-
defined task is done by a highly cohesive method. The weakly cohesive method will split the task
into separate parts. The java.io package is a highly cohesive package because it has I/O related
classes and interface. However, the java.util package is a weakly cohesive package because it has
unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be associated with
one object or many objects. There can be four types of association between the objects:
One to One
One to Many
Many to One, and
Many to Many
Let's understand the relationship with real-time examples. For example, One country can have one
prime minister (one to one), and a prime minister can have many ministers (one to many). Also,
many MP's can have one prime minister (many to one), and many ministers can have many
departments (many to many).
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one
object contains other objects as a part of its state. It represents the weak relationship between objects.
It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is
another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the relationship
where one object contains other objects as a part of its state. There is a strong relationship between
the containing object and the dependent object. It is the state where containing objects do not have an
independent existence. If you delete the parent object, all the child objects will be deleted
automatically.
Naming Conventions
Class
It should start with the uppercase letter.
It should be a noun such as Color, Button, System, Thread, etc.
Use appropriate words, instead of acronyms.
Interface
It should start with the uppercase letter.
It should be an adjective such as Runnable, Remote, ActionListener.
Use appropriate words, instead of acronyms.
Method
It should start with lowercase letter.
It should be a verb such as main(), print(), println().
If the name contains multiple words, start it with a lowercase letter followed by an
uppercase letter such as actionPerformed().
Variable
It should start with a lowercase letter such as id, name.
It should not start with the special characters like & (ampersand), $ (dollar), _
(underscore).
If the name contains multiple words, start it with the lowercase letter followed by an
uppercase letter such as firstName, lastName.
Avoid using one-character variables such as x, y, z.
Package
It should be a lowercase letter such as java, lang.
If the name contains multiple words, it should be separated by dots (.) such as java.util,
java.lang.
Constant
It should be in uppercase letters such as RED, YELLOW.
If the name contains multiple words, it should be separated by an underscore(_) such as
MAX_PRIORITY.
It may contain digits but not as the first letter.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Access Specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Types of Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
Constructors in Java
It is a special type of method which is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.
Rules for creating Java constructor
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
Types of Java constructors
Inheritance
The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child
relationship.
Terms used in Inheritance
Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same
fields and methods already defined in the previous class.
extends: keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
Types of inheritance in java
Single Inheritance:
Multilevel Inheritance
Hierarchical Inheritance
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
Java final method: If you make any method as final, you cannot override it.
Java final class :If you make any class as final, you cannot extend it.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It 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.
Example of Abstract class that has an abstract method
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
Interface inheritance :A class implements an interface, but one interface extends another
interface.
2) import package.classname;
3) fully qualified name.
if you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Exception Handling in Java
The Exception Handling in Java is one of the powerful mechanisms to handle the runtime errors
so that the normal flow of the application can be maintained.
What is Exception in Java?
Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
What is Exception Handling?
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Hierarchy of Java Exception classes
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable.Some example of errors are OutOfMemoryError, VirtualMachineError,
AssertionError etc
Java Exception Keywords
Try: The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or finally.
Catch: The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
Finally: The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not
Throw: The "throw" keyword is used to throw an exception
Throws: The "throws" keyword is used to declare exceptions. It specifies that there may occur
an exception in the method. It doesn't throw an exception. It is always used with method
signature.
What is classloader?
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader. There are three built-in classloaders in Java.
Bootstrap ClassLoader:
Extension ClassLoader:
System/Application ClassLoader:
If I don't provide any arguments on the command line, then what will the value stored in
the String array passed into the main() method, empty or NULL?
It is empty, but not null
What if I write static public void instead of public static void?
The program compiles and runs correctly because the order of specifiers doesn't matter in Java.
What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object
references.
Can we make constructors static?
As we know that the static context (method, block, or variable) belongs to the class, not the
object. Since Constructors are invoked only when the object is created, there is no sense to make
the constructors static. However, if you try to do so, the compiler will show the compiler error.
Can we make the abstract methods static in Java?
In Java, if we make the abstract methods static, It will become the part of the class, and we can
directly call it which is unnecessary. Calling an undefined method is completely useless
therefore it is not allowed.
What are the main uses of this keyword?
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known
as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to
Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.
Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.
It makes the code compact but complex to understand.
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It
provides the implementation of all the methods of these interfaces except the service
method.
GenericServlet class can handle any type of request so it is protocol-independent.
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface.
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
Cookies in servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
Types of Cookies
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session. It is not removed each time when user closes the browser. It is
removed only if user logout or sign-out.