You are on page 1of 9

Java:

Java is a popular programming language, created in 1995. It is owned by Oracle, and more
than 3 billion devices run Java. It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Games
 Database connection
Why Use Java?

 Java works on different platforms (Windows, Mac, Linux, etc.)


 It is one of the most popular programming language in the world
 It is easy to learn and simple to use
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to programs and
allows code to be reused, lowering development costs
Syntax:
public class Hello
{
public static void main(String[] args)
{
System.out.println("Hello Java");
}
}
File Handling in Java:
File handling in Java implies reading from and writing data to a file. The File class from the
java.io package, allows us to work with different formats of files. File handling provides a
mechanism to store the output of a program in a file and to perform various operations on
it.
Java has several methods for creating, reading, updating, and deleting files. The file class has
many useful methods for creating and getting information about files. For example:
Method Type Description
canRead() Boolean It tests whether the file is readable or not
canWrite() Boolean It tests whether the file is writable or not
createNewFile() Boolean This method creates an empty file
delete() Boolean Deletes a file
exists() Boolean It tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory

Create a file: To create a file in Java, you can use the createNewFile() method.


This method returns a Boolean value: true if the file was successfully created, and false if the
file already exists. Note that the method is enclosed in a try...catch block. This is necessary
because it throws an IOException if an error occurs (if the file cannot be created for some
reason):

To create a file in a specific directory (requires permission), specify the path of the file and
use double backslashes to escape the "\" character (for Windows).
Java Exceptions:
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
An exception (or exceptional event) is a problem that arises during the execution of a
program. When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.

 Physical limitations (out of disk memory)


 Code errors
 Opening an unavailable file
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications
Exception Categories:
Checked exceptions − A checked exception is an exception that is checked (notified) by the
compiler at compilation-time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer should take care of (handle) these
exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the
compiler prompts the programmer to handle the exception.
Unchecked exceptions − An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of
compilation.
For example, if you have declared an array of size 5 in your program, and trying to call the
6th element of the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Java try and catch: The try statement allows you to define a block of code to be tested for
errors while it is being executed.
The catch statement allows you to define a block of code to be executed, if an error occurs
in the try block. The try and catch keywords come in pairs.
Java built-in Exceptions:
ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted.
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.
Java Inheritance:
Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword. A very important fact to remember is that Java does not support multiple
inheritance. This means that a class cannot extend more than one class.
Example: Public class extends Animal, Mammals. However, a class can implement one or
more interfaces, which has helped Java get rid of the impossibility of multiple inheritance.
Syntax:
class Superclass
{
..... .....
}
class Sub extends Superclass
{
..... .....
}
Single inheritance: In this inheritance, a derived class is created from a single base class.
Multi-level inheritance: In this inheritance, a derived class is created from another derived
class.
Hierarchical Inheritance: In this inheritance, more than one derived classes are created
from a single base class and futher child classes act as parent classes for more than one child
classes.
Multiple inheritance: In this inheritance, a derived class is created from more than one base
class. This inheritance is not supported by .NET Languages like C#, F# etc. and Java
Language.
The super keyword:

 It is used to differentiate the members of superclass from the members of subclass,


if they have same names.
 It is used to invoke the superclass constructor from subclass.
 Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the superclass
have the names same as the sub class, to differentiate these variables we use super
keyword.
Overriding in java:
In object-oriented terms, overriding means to override the functionality of an existing
method.
In any object-oriented programming language, Overriding is a feature that allows a subclass
or child class to provide a specific implementation of a method that is already provided by
one of its super-classes or parent classes.
When a method in a subclass has the same name and same return type as a method in its
super-class, then the method in the subclass is said to override the method in the super-
class.
Java – Encapsulation:
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on
the data (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
hiding.
To achieve encapsulation in Java −

 Declare the variables of a class as private.


 Provide public setter and getter methods to modify and view the variables values.
The public set() and get() methods are the access points of the instance variables of the
EncapTest class.
Normally, these methods are referred as getters and setters. Therefore, any class that wants
to access the variables should access them through these getters and setters.
Method Overloading:
Method Overloading is a feature that allows a class to have more than one method having
the same name, if their argument lists are different. 
Abstraction in Java: ABSTRACTION is the concept of object-oriented programming that
"shows" only essential attributes and "hides" unnecessary information. The main purpose
of abstraction is hiding the unnecessary details from the users.
It helps in reducing programming complexity and efforts. It is one of the most important
concepts of OOPs.
Abstract class: An abstract class is one that contains the keyword abstract.
Abstract methods: An abstract method is one that contains the keyword abstract. An
abstract method doesn’t have implementation (no method body and ends up with a semi
colon). It shouldn’t be marked as private.

When to use Abstract Methods & Abstract Class?


Abstract methods are mostly declared where two or more subclasses are also doing the
same thing in different ways through different implementations. It also extends the same
Abstract class and offers different implementations of the abstract methods.
Abstract classes describes subclasses to offer implementation details of the abstract class.
Interface:
An interface is similar to class. It is a collection of abstract methods. A class implements an
interface, thereby inheriting the abstract methods of the interface.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
An interface is different from a class in several ways, including −

 An interface does not contain any constructors.


 All of the methods in an interface are abstract.
 An interface is not extended by a class; it is implemented by a class.

Polymorphism in Java:
Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance.
Inheritance lets us inherit attributes and methods from another class. Polymorphism uses
those methods to perform different tasks. This allows us to perform a single action in
different ways.
Compile time Polymorphism (or Static polymorphism)
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading is an example of compile time polymorphism.
Runtime Polymorphism (or Dynamic polymorphism):
Dynamic polymorphism is a process in which a call to an overridden method is resolved at
runtime, that's why it is called runtime polymorphism.
Java Inner Classes:
Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be
more readable and maintainable.
Additionally, it can access all the members of outer class including private data members
and methods.
Advantage of java inner classes:
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Java Package:
A package as the name suggests is a pack(group) of classes, interfaces and other packages.
In java we use packages to organize our classes and interfaces.
We have two types of packages in Java: built-in packages and the packages we can create
(also known as user defined package).
Types of packages in Java:
1) User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as
built-in packages.
Advantages of using a package in Java:
These are the reasons why you should use packages in Java:
Reusability: While developing a project in java, we often feel that there are few things that
we are writing again and again in our code. Using packages, you can create such things in
form of classes inside a package and whenever you need to perform that same task, just
import that package and use the class.
Better Organization: Again, in large java projects where we have several hundreds of
classes, it is always required to group the similar types of classes in a meaningful package
name so that you can organize your project better and when you need something you can
quickly locate it and use it, which improves the efficiency.
Name Conflicts: We can define two classes with the same name in different packages so to
avoid name collision, we can use packages

Java Access Modifiers:


You must have seen public, private and protected keywords while practicing java programs,
these are called access modifiers.
An access modifier restricts the access of a class, constructor, data member and method in
another class.
In java we have four access modifiers:
1. default
2. private
3. protected
4. Public
Public access modifier: The members, methods and classes that are declared public can be
accessed from anywhere. This modifier doesn’t put any restriction on the access.
Private access modifier: Methods, variables, and constructors that are declared private can
only be accessed within the declared class itself. Private access modifier is the most
restrictive access level. Class and interfaces cannot be private.
Protected Access Modifier: Variables, methods, and constructors, which are declared
protected in a superclass can be accessed only by the subclasses in other package or any
class within the package of the protected members' class. The protected access modifier
cannot be applied to class and interfaces.
Default Access modifier: When no access modifier is specified for a class, method or data
member – It is said to be having the default access modifier by default.
The data members, class or methods which are not declared using any access modifiers i.e.
having default access modifier are accessible only within the same package.
Java Abstract Window Toolkit (AWT): Java AWT contains large number of classes and
methods to create and manage graphical user interface ( GUI ) applications.
The AWT was designed to provide a common set of tools for GUI design that could work on
a variety of platforms.

You might also like