Java Unit-1 Notes
Java Unit-1 Notes
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the Oak name to
Java.
Features of Java : The features of Java are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun, Java language is a simple programming language because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.
Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporates both data and behavior.
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on the top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
No explicit pointer
Java Programs run inside a virtual machine sandbox
Cla
ssloader: Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network
sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate access right to
objects.
Security Manager: It determines what resources a class can access such as reading and writing
to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example,
the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes
of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
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++). Java is
an interpreted language that is why it is slower than compiled languages, e.g., C, C++, 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.
Multi-threaded
A thread is like a separate program, executing concurrently. 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.
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++.
Java supports dynamic compilation and automatic memory management (garbage collection).
Token : The basic building blocks of a program. They are the smallest individual units of a
program that have meaning to the compiler and are used to represent the various elements of a
program, such as keywords, identifiers, operators, and literals.
LITERALS : Literals represent fixed values in a source code. These are similar to standard variables with
the difference that these are constant. These can be classified as an integer literal, a string literal, a
boolean etc. The user defines these mainly to define constants.
INT 4 byte
CHAR 2 byte
FLOAT 4 byte
DOUBLE 8 byte
SHORT 2 byte
BOOLEAN 1 byte
LONG 8 byte
Operator Examples
Arithmetic +.-.*,/,%
Assignment =.+=,-=,*=,/=
Unary ++,--,≠
Logical &&,||
Relational ==,≠,≥,≤
Ternary condition?stat1:stat2
Bitwise &,|,~,^
Shift >>,<<,>>>
Separators : These are the special symbols used to separate java tokens. These are sometimes called
punctuators.
Brackets []: These are used to define arrays and represent single and multi-dimension subscripts.
Braces {}: These mark the start and end of multi-line code blocks.
Assignment operator (=): It assigns values to variables. For example, a=10, here we are giving value
10 to variable 'a'.
Keywords : Keywords are reserved words in programming languages. These are used to indicate
predefined terms and actions in a program.
Identifiers in Java are a sequence of characters to identify something in a program. They are names
given to a class, variable, package, method, or interface and allow the programmer to refer to the
specific item from any place in the program.
Identifiers are case-sensitive. That is, “ninja” is not the same as “NINJA”.
Identifier names should not start with a digit. For example, “007IamNinja” is an invalid identifier.
They are used to define a fixed set of constants representing a distinct type.
Enums can have methods, constructors, and fields, making them more powerful and versatile.
Enum constants are objects, allowing you to attach behavior to each constant.
Example:
Copy
Constants: Constants in Java are typically declared using the final keyword.
They are static and final variables, and their values cannot be changed once assigned.
Example:
Copy
In Java, public, private, and protected are access modifiers used to control the visibility and accessibility
of classes, methods, and variables within a program.
Public: When a class, method, or variable is declared as public, it can be accessed from any other class.
Private: When a class member is declared as private, it can only be accessed within the same class.
It provides a high level of encapsulation, limiting access to the internal details of the class.
Protected: The protected modifier allows access within the same class, subclasses, and classes in the
same package. It provides a balance between the openness of public and the encapsulation of private.
Class:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
Fields
Methods
Constructors
Blocks (Instance Initialization Block (IIB), Static Initialization Block (SIB))
Nested class and interface
class <class_name>{
field;
method;
The answer is Yes, some classes can be made static in Java. Java supports
Java allows a class to be defined within another class. These are called Nested Classes. The class
in which the nested class is defined is known as the Outer Class. Unlike top-level classes, Inner
classes can be Static. Non-static nested classes are also known as Inner classes.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors
of a parent object. It is an important part of OOPs (Object Oriented programming system).
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.
The 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.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
A class that 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.
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
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 that will force the subclass not to change the body of the method.
An abstract class can have a data member, abstract method, method body (non-abstract method),
constructor, and even main() method.
Polymorphism in Java is a concept by which we can perform a single action in
different ways. The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here,
we will focus on runtime polymorphism in java.
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
By providing only a setter or getter method, you can make the class read-only or write-only. In other
words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should be
greater than 100 only, you can write the logic inside the setter method. You can write the logic not to
store the negative numbers in the setter methods.
It is a way to achieve data hiding in Java because other class will not be able to access the data through
the private data members.
The encapsulate class is easy to test. So, it is better for unit testing.
The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to
create an encapsulated class in Java.
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.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters
then it may be difficult for you as well as other programmers to understand the behavior of the method
because its name differs.
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.
class Adder
class TestOverloading1{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output: 22 33
class Adder{
class TestOverloading2{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output: 22 24.9
EXCEPTION TYPE:
These are exceptions that the compiler requires you to These are exceptions that do not need to be explicitly
handle. handled by the programmer.
They are subclasses of Exception (excluding They are subclasses of RuntimeException and typically
RuntimeException and its subclasses) indicate programming errors
Example : Example :
Exception Handling:
The try block encloses the code that might throw an exception.
The catch block contains the code that handles the exception if it occurs. Multiple catch blocks can be
used to handle different types of exceptions.
The finally block contains code that will be executed regardless of whether an exception occurs or not.
Errors are exceptional situations that are typically Exceptions, represent conditions that a reasonable
beyond the control of the programmer. application might want to catch and handle.
They are usually caused by the environment or system They can be caused by errors in the program logic or by
failures, and they are considered serious issues. external factors such as user input or network issues.
Generally, errors are not caught or handled by the Exceptions are meant to be caught and handled by the
application but are meant to indicate severe problems programmer to ensure a graceful degradation of the
that should be addressed at a higher level. application in the face of unexpected issues.
In Java, try, catch, and throw are keywords used for exception handling. Exception
handling is a mechanism that allows you to gracefully handle errors or exceptional
situations in your code, preventing the program from crashing.
try: The try block encloses a section of code where an exception might occur. It is
followed by one or more catch blocks.
catch: The catch block is used to handle specific types of exceptions that may be
thrown in the try block. You can have multiple catch blocks to handle different
types of exceptions.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
try {
readFile("example.txt");
catch (FileNotFoundException e) {
catch (IOException e) {
finally {