Java Porgramming Part 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 37

JAVA PROGRAMMING

What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.

List the features of Java Programming language.


Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the
program in it.
Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as
the combination of different type of objects that incorporates both data and behavior.
Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on
every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on
every machine.
Platform Independent: Java is a platform independent programming language. It is different from
other programming languages like C and C++ which needs a platform to be executed. Java comes
with its platform on which its code is executed. Java doesn't depend upon the operating system to be
executed.
Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of
ByteCode and Exception handling which makes it more secured.
Robust: Java is a strong programming language as it uses strong memory management. The concepts
like Automatic garbage collection, Exception handling, etc. make it more robust.
Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the
size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program
execution.
High Performance: Java is faster than other traditional interpreted programming languages because
Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C+
+).
Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple
threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web applications, etc.
Distributed: Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes us able to
access files by calling the methods from any machine on the internet.
Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't
physically exist. It is a specification that provides a runtime environment in which Java bytecode can
be executed. It can also run those programs which are written in other languages and compiled to
Java bytecode.

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.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

List of Java Keywords


1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the
implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and
False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current flow
of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be
used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the
program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always
private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a
variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always
executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions
repeatedly when some condition becomes true. If the number of iterations is fixed, it is
recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the current
source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified
class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code using
JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the
garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or variable
may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the package and
outside the package but through inheritance only. It can't be applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is accessible
anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The static
keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects. It can
be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods in
multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is
mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block
must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program
several times. If the number of iterations is not fixed, it is recommended to use the while loop.

Java Control Statements

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

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
} }
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Java static keyword
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs to the
class than an instance of the class.
1) Java static variable
If you declare any variable as static, it is known as a static variable. The static variable gets
memory only once in the class area at the time of class loading.

Java static method


If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.

Java static block


 Is used to initialize the static data member.
 It is executed before the main method at the time of classloading.

this keyword in Java


There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.

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

Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

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.

2. super can be used to invoke immediate parent class method:


The super keyword can also be used to invoke parent class method. It should be used if subclass
contains the same method as parent class. In other words, it is used if method is overridden.
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.
To call the parent class method, we need to use super keyword.

3. super() can be used to invoke immediate parent class constructor

Final Keyword in Java


The final keyword in java is used to restrict the user. The java final keyword can be used in
many contexts. Final can be:
 variable
 method
 class
Java final Variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).

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.

Abstract class having constructor, data member and methods


An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction
There can be only abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Java Interface also represents the IS-A relationship.
Why use Java interface?
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritance.
 It can be used to achieve loose coupling.
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is provided
in the A6 class.
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known
as multiple inheritance.

Multiple inheritance is not supported through class in java, but it is possible by an


interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case
of class
because of ambiguity. However, it is supported in case of an interface because there is no
ambiguity. It is because its implementation is provided by the implementation class. For
example:

Interface inheritance :A class implements an interface, but one interface extends another
interface.

Nested Interface in Java


Note: An interface can have another interface which is known as a nested interface. We will
learn it in detail in the nested classes chapter. For example:

Abstract Class vs Interface


Java Package:
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
 Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
 Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 Java package provides access protection.
 Java package removes naming collision.
How to access package from another package?
There are three ways to access the package from outside the package.
1) import package.*;

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.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

Common Scenarios of Java Exceptions


a. A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.

b. A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

c. A scenario where NumberFormatException occurs


If the formatting of any variable or number is mismatched, it may result into
NumberFormatException.
Suppose we have a string variable that has characters; converting this variable into digit will
cause NumberFormatException.

d. A scenario where ArrayIndexOutOfBoundsException occurs


When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

What is the platform?


 A platform is the hardware or software environment in which a piece of software is
executed.
 There are two types of platforms, software-based and hardware-based. Java provides the
software-based platform.

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?

 this can be used to refer to the current class instance variable.


 this can be used to invoke current class method (implicitly)
 this() can be used to invoke the current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as an argument in the constructor call.
 this can be used to return the current class instance from the method.
What is composition?
Holding the reference of a class within some other class is known as composition.
When an object contains the other object, if the contained object cannot exist without the
existence of container object, then it is called composition. In other words, we can say that
composition is the particular case of aggregation which represents a stronger relationship
between two objects. Example: A class contains students. A student cannot exist without a class.
There exists composition between class and students.
What is the difference between aggregation and composition?
Aggregation represents the weak relationship whereas composition represents the strong
relationship. For example, the bike has an indicator (aggregation), but the bike has an engine
(composition).
Why does Java not support pointers?
The pointer is a variable that refers to the memory address. They are not used in Java because
they are unsafe(unsecured) and complex to understand.
What is object cloning?
The object cloning is used to create the exact copy of an object.
The clone() method of the Object class is used to clone an object. The java.lang.Cloneable
interface must be implemented by the class whose object clone we want to create.
If we don't implement Cloneable interface, clone() method generates
CloneNotSupportedException.
protected Object clone() throws CloneNotSupportedException
Can we override the static method?
No, you can't override the static method because they are the part of the class, not the object.
Why can we not override static method?
It is because the static method is the part of the class, and it is bound with class whereas instance
method is bound with the object, and static gets memory in class area, and instance gets memory
in a heap.
Can we override the overloaded method?
Yes.
Method Overloading in Java
If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program
Advantage of method overloading
Method overloading increases the readability of the program.
Different ways to overload the method
 By changing number of arguments
 By changing the data type

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add () method performs addition of two
numbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
calling methods.
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type
The first add method receives two integer arguments and second add method receives two
double arguments.

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
class Parent
{
void show ()
{
System.out.println("Parent's show()");
}
}
// Inherited class
class Child extends Parent {
void show()
{
System.out.println("Child's show()");
}
}
// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show is called
Parent obj1 = new Parent();
obj1.show();
// If a Parent type reference refers to a Child object Child's show() is called. This is called
RUN TIME POLYMORPHISM.
Parent obj2 = new Child();
obj2.show();
}
}
Output:
Parent's show()
Child's show()

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.
Autoboxing and unboxing feature convert primitives into objects and objects into primitives
automatically. The automatic conversion of primitive into an object is known as autoboxing and
vice-versa unboxing.

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:

 JDBC-ODBC Bridge Driver,


 Native Driver,
 Network Protocol Driver, and
 Thin Driver
What is a Servlet?
 Servlet can be described in many ways, depending on the context.
 Servlet is a technology which is used to create a web application.
 Servlet is an API that provides many interfaces and classes including documentation.
 Servlet is an interface that must be implemented for creating any Servlet.
 Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
 Servlet is a web component that is deployed on the server to create a dynamic web
page.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.

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.

You might also like