0% found this document useful (0 votes)
56 views19 pages

Java Unit-1 Notes

Java is a high-level, robust, object-oriented, and secure programming language developed by Sun Microsystems in 1995. It is a platform that runs on a Java Virtual Machine (JVM) and uses bytecode that is portable across various operating systems. Some key features of Java include its simplicity, object-oriented design, portability, security, and ability to be used for both standalone and web-based applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
56 views19 pages

Java Unit-1 Notes

Java is a high-level, robust, object-oriented, and secure programming language developed by Sun Microsystems in 1995. It is a platform that runs on a Java Virtual Machine (JVM) and uses bytecode that is portable across various operating systems. Some key features of Java include its simplicity, object-oriented design, portability, security, and ability to be used for both standalone and web-based applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 19

Java is a programming language and a platform.

Java is a high level, robust, object-oriented


and secure programming language.

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.

Platform: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

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.

Object-oriented programming (OOPs) is a methodology that simplifies software development


and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is


different from other languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A platform is the hardware or
software environment in which a program runs.

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

Robust simply means strong. Java is robust because:

 It uses strong memory management.


 There is a lack of pointers that avoids security problems.
 There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid
of objects which are not being used by a Java application anymore.
 There are exception handling and the type checking mechanism in Java. All these points make
Java 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.

Syntax of Literals : final data_type variable_name;


Data Type Size

INT 4 byte

CHAR 2 byte
FLOAT 4 byte

DOUBLE 8 byte

SHORT 2 byte

BOOLEAN 1 byte

LONG 8 byte

OPERATOR : operators perform operations between different entities

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.

 Parenthesis (): Used for function calls and parameters.

 Comma (,): These separate statements. For example, separate parameters.

 Semicolon ( : ): It invokes the initialization list.

 Asterisk (*): This is used to generate pointer variables.

 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.

abstract assert boolean break byte


case catch char class continue
default do double else enum
extends final finally float for
if implements import instanceof int
interface long native new null
package private protected public return
short static strictfp super switch
synchronised this throw throws transient
try void volatile while const/goto

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.

public class Test

public static void main(String[] args)

int num = 10;

Identifiers present in the above program are:

Test: The name of the class.

main: The name of a method.

String: A predefined class name.

args: A variable name.

num: A variable name.


There are rules for naming identifiers.

 The characters allowed are [A-Z], [a-z], [0-9], _ and $.

 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.

 Whitespace is not allowed inside an identifier.

 Keywords can’t be used as an identifier.

ENUM and COSTANT DIFFERENCE

Enums: Enums are a special data type in Java introduced in Java 5.

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

public enum Day {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

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.

Constants are usually used to represent unchanging values or configuration settings.

Constants cannot have methods or constructors.

Example:

Copy

public class Constants {

public static final int MAX_VALUE = 100;


public static final String APP_NAME = "MyApp";

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.

There are no restrictions on its visibility.

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.

A class in Java can contain:

 Fields
 Methods
 Constructors
 Blocks (Instance Initialization Block (IIB), Static Initialization Block (SIB))
 Nested class and interface

Syntax to declare a class:

class <class_name>{

field;

method;

an a class be static in Java?

The answer is Yes, some classes can be made static in Java. Java supports

 Static Instance Variables


 Static Methods,
 Static Block
 Static Classes

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.

Why use inheritance in java:

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.
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.
The syntax of Java Inheritance:

class Subclass-name extends Superclass-name

//methods and fields

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.

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Abstract class 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.

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time. In this process, an overridden method is called
through the reference variable of a superclass. The determination of the method to be called is based on
the object being referred to by the reference variable.

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.

Advantage of Encapsulation in Java

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.

So, we perform method overloading to figure out the program quickly.

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

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.

class Adder

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

class TestOverloading1{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(11,11,11));

}}

Output: 22 33

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.

class Adder{

static int add(int a, int b){return a+b;}

static double add(double a, double b){return a+b;}

class TestOverloading2{

public static void main(String[] args){

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

Output: 22 24.9

INTRODUCTION to EXCEPTION. DIFFERENCE BETWEEN ERROR AND EXCEPTION.


In Java, exceptions are a mechanism for handling runtime errors, which are unexpected events that
occur during the execution of a program. These errors can disrupt the normal flow of a program and
may lead to abnormal termination if not properly handled. Java provides a robust exception-handling
mechanism to deal with such situations, and this is achieved through the use of the try, catch, throw,
and finally keywords.

EXCEPTION TYPE:

Checked Exceptions Unchecked Exceptions (Runtime Exceptions)

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 :

IOException and ClassNotFoundException. NullPointerException and


ArrayIndexOutOfBoundsException.

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.

Difference between Error and Exception in Java:


ERROR EXCEPTION

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.

Examples: OutOfMemoryError, StackOverflowError, and Exmple : ArithmeticException


LinkageError.

USE of TRY, CATCH and THROW :

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.

throw: The throw keyword is used to explicitly throw an exception. It is generally


used when you want to signal that something unexpected or erroneous has
happened in your code.

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class ExceptionHandlingExample {

public static void main(String[] args) {

try {

readFile("example.txt");

catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

catch (IOException e) {

System.out.println("IO Exception: " + e.getMessage());

finally {

System.out.println("Finally block always executes.");


}

public static void readFile(String filename) throws FileNotFoundException,


IOException {

try (FileReader fileReader = new FileReader(filename)) {

// Code to read from the file

In this example, the readFile method is declared to throw FileNotFoundException


and IOException. The main method then tries to call readFile, and if any
exception occurs, it catches and handles the specific exception types. The finally
block is optional and will be executed regardless of whether an exception occurs
or not.

Diference betwwn throw nd throws in java :

Feature Throw Throws


Purpose Used to explicitly throw an Used in method signature to
exception within a method or declare that the method may
block of code. throw one or more exceptions.

Usage Inside a method or block of code In the method declaration to


to throw an exception explicitly. indicate that the method might
throw an exception.

Impact on It does not affect method Affects method signature,


Method signature. indicating potential exceptions
Signature that the method might throw.

Handling The thrown exception must be Methods calling this method


caught using a try-catch block. need to handle the declared
exceptions using try-catch or
propagate them further with
throws clause

Syntax throw <exception>; void methodName() throws


<exceptionType>;

You might also like