0% found this document useful (0 votes)
4 views12 pages

Java Unit 1

Java is a high-level, object-oriented programming language known for its platform independence, robust features, and rich standard library. Key concepts include classes and objects, encapsulation, inheritance, abstraction, and polymorphism, which facilitate modular and reusable code. The Java environment consists of the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), enabling developers to write, compile, and run Java applications efficiently.

Uploaded by

panwar080304
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views12 pages

Java Unit 1

Java is a high-level, object-oriented programming language known for its platform independence, robust features, and rich standard library. Key concepts include classes and objects, encapsulation, inheritance, abstraction, and polymorphism, which facilitate modular and reusable code. The Java environment consists of the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), enabling developers to write, compile, and run Java applications efficiently.

Uploaded by

panwar080304
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Unit 1

Java is a high-level, class-based, object-oriented programming language designed to have as few


implementation dependencies as possible. It was originally developed by James Gosling at Sun
Microsystems (which has since been acquired by Oracle Corporation) and released in 1995.

Characteristics/Features of Java:
1. Platform Independence: Java is designed to be platform-independent at both the source and
binary levels. This is achieved through the use of the Java Virtual Machine (JVM), which allows
Java programs (compiled into bytecode) to run on any device equipped with a JVM.
2. Object-Oriented: It follows an object-oriented programming paradigm, which means it
organizes software design around data, or objects, rather than functions and logic. This helps in
creating modular programs and reusable code.
3. Simple and Familiar Syntax: Java's syntax is similar to C++ lang, making it easier for
programmers with a background in C/JAVA to learn and use. However, Java removes many of
the complex and error-prone features such as pointers and multiple inheritance.
4. Robust and Secure: Java emphasizes early checking for possible errors, as it compilers can
detect many problems that would only show up during execution time in other languages. It also
provides a secure environment through its runtime constraints and security features.
5. Automatic Memory Management: It handles memory allocation and deallocation automatically
through its garbage collection mechanism, which helps in managing memory more efficiently
and reducing the risk of memory leaks.
6. Multithreading: It has built-in support for multithreaded programming, which allows developers
to write programs that can perform multiple tasks simultaneously.
7. Rich Standard Library: Java comes with a comprehensive standard library (Java Standard Edition
or SE) that provides many useful tools and utilities, such as collections frameworks,
input/output, networking, data structures, and more.
8. Development Tools: There are many development tools available for Java, including integrated
development environments (IDEs) like Eclipse, IntelliJ IDEA, and NetBeans, which provide
powerful features to assist in coding, debugging, and managing Java projects.
9. Community and Ecosystem: Java has a large and active community of developers, and a vast
ecosystem of libraries, frameworks, and tools that support development across various
domains, including web applications, enterprise solutions, mobile apps (via Android), and more.
10. Versions and Updates: Java is regularly updated with new features and improvements. Major
versions of Java are released periodically, with Long-Term Support (LTS) versions providing
extended support and stability for enterprise applications.

Core Components of Java

1. Java Development Kit (JDK): A software development environment used for developing Java
applications. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a
compiler (javac), an archiver (jar), and documentation generator (Javadoc).
2. Java Runtime Environment (JRE)Provides the libraries, Java Virtual Machine (JVM), and other
components to run applications written in Java.
3. Java Virtual Machine (JVM): An abstract machine that enables your computer to run a Java
program. It converts Java bytecode into machine-specific code.

What is object?
In JAVA, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc. In other words,
object is an entity that has state and behavior. Here, state means data and behavior means
functionality. Object is a runtime entity; it is created at runtime. Object is an instance of a class. All the
members of the class can be accessed through object.

What is class?
A class is a blueprint for creating objects. It defines a data structure by encapsulating data (fields) and
behavior (methods) into a single unit. A class specifies what an object of that type will contain and what
operations can be performed on those objects.

Key components of a class:


1. Fields (Attributes): Variables that store the state of an object.
2. Methods: Functions that define the behavior of an object.
3. Constructors: Special methods used to initialize objects.
4. Modifiers: Keywords that define the visibility and behavior of classes, methods, and fields (e.g.,
public, private, protected, static, final).

Example of Class and Object:

Principles of OOP
1. Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and information under a single unit.
In Object-Oriented Programming, Encapsulation is defined as binding together the data and the
functions that manipulate them. Consider a real-life example of encapsulation, in a company, there
are different sections like the accounts section, finance section, sales section, etc. The finance
section handles all the financial transactions and keeps records of all the data related to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of all the sales.
Now there may arise a situation when for some reason an official from the finance section needs all
the data about sales in a particular month. In this case, he is not allowed to directly access the data
of the sales section. He will first have to contact some other officer in the sales section and then
request him to give the particular data. This is what encapsulation is. Here the data of the sales
section and the employees that can manipulate them are wrapped under a single name “sales
section”.

What is difference between encapsulation and data hiding?


Data hiding helps prevent the illegal or unauthorized access of members of a class, while
encapsulation helps in the wrapping up of data members and methods inside a class.

2. Inheritance
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
Inheritance is a feature or a process in which, new classes are created from the existing classes. The
new class created is called “derived class” or “child class” and the existing class is known as the
“base class” or “parent class”. The derived class now is said to be inherited from the base class.
When we say derived class inherits the base class, it means, the derived class inherits all the
properties of the base class, without changing the properties of base class and may add new
features to its own. These new features in the derived class will not affect the base class. The
derived class is the specialized class for the base class.
Sub Class: The class that inherits properties from another class is called Subclass or Derived Class.
Super Class: The class whose properties are inherited by a subclass is called Base Class or
Superclass.

class <derived_class_name> extends <base_class_name>{

//body

3. Abstraction
Data abstraction is one of the most essential and important features of object-oriented
programming in JAVA. Abstraction means displaying only essential information and hiding the
details. Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. Consider a real-life example of a man
driving a car. The man only knows that pressing the accelerator will increase the speed of the car or
applying brakes will stop the car but he does not know how on pressing the accelerator the speed is
actually increasing, he does not know about the inner mechanism of the car or the implementation
of an accelerator, brakes, etc. in the car. This is what abstraction is.
4. Polymorphism
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-life
example of polymorphism is a person who at the same time can have different characteristics. A
man at the same time is a father, a husband, and an employee. So, the same person exhibits
different behavior in different situations. This is called polymorphism. Polymorphism is considered
one of the important features of Object-Oriented Programming.

Polymorphism are of two types:


1. Compile-Time Polymorphism
• Function Overloading: When there are multiple functions with the same name but
different parameters, then the functions are said to be overloaded, hence this is known
as Function Overloading. Functions can be overloaded by changing the number of
arguments or/and changing the type of arguments. In simple terms, it is a feature of
object-oriented programming providing many functions that have the same name but
distinct parameters when numerous tasks are listed under one function name.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and dynamic
polymorphism are other names for runtime polymorphism. The function call is resolved at
runtime in runtime polymorphism. In contrast, with compile time polymorphism, the compiler
determines which function call to bind to the object after deducing it at runtime.
Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.

Tokens
In Java, tokens are the smallest units in a program that are meaningful to the compiler. They are the
building blocks of Java programs and include keywords, identifiers, literals, operators, separators, and
comments. Here's a detailed overview of the different types of tokens in Java:
1. Keywords: Keywords are reserved words that have a predefined meaning in Java. They cannot
be used as identifiers (names for variables, classes, methods, etc.). Examples include ‘class’,
‘public’, ‘static’, ‘void’, etc.
2. Identifiers: Identifiers are names given to various program elements such as variables, methods,
classes, and interfaces. They must begin with a letter, a dollar sign $, or an underscore _ and can
be followed by any combination of letters, digits, dollar signs, and underscores.
3. Literals: Literals are constant values that are directly represented in the code. Java supports
several types of literals, including:
• Integer Literals: int a = 100;
• Floating-point Literals: double b = 3.14;
• Character Literals: char c = 'A';
• String Literals: String str = "Hello";
• Boolean Literals: boolean flag = true;
4. Operators are special symbols that perform operations on variables and values. Java has several
types of operators, including:
• Arithmetic Operators: +, -, *, /, %
• Relational Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• Assignment Operators: =, +=, -=, *=, /=, %=
• Increment/Decrement Operators: ++, --
5. Separators: Separators help define the structure of a program. They include:
• Parentheses: ()
• Braces: {}
• Brackets: []
• Semicolon: ;
• Comma: ,
• Dot: .
6. Comments: Comments are not executed by the Java compiler and are used to provide
explanations or annotations within the code. Java supports three types of comments:
• Single-line comments: Start with // and continue to the end of the line.
• Multi-line comments: Start with /* and end with */.

Documentation comments: Start with /** and end with */. These are used by the Javadoc tool
to generate API documentation.

The Java Environment


The Java environment consists of a comprehensive set of tools and technologies that allow developers
to write, compile, and run Java applications. Here's a detailed look at the components and processes
involved in the Java environment:

Java Source File


A Java source file contains code written in the Java programming language. It has the extension .java
and typically contains one or more classes, interfaces, or enums. The file name should match the name
of the public class or interface defined within it.

Structure of a Java Source File: A typical Java source file consists of the following elements:

1. Package Declaration (optional): Specifies the package to which the class belongs.
package [Link];

2. Import Statements (optional): Import other Java classes or packages.


import [Link];

3. Class/Interface Declaration: Defines the main structure of the class or interface.


public class Main {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

Compilation

Compilation is the process of converting Java source code into bytecode, which can be
executed by the Java Virtual Machine (JVM). The Java compiler (javac) is used for this purpose.

Steps in the Compilation Process:

1. Write the Source Code: Create a .java file with the source code.
2. Compile the Source Code: Use the javac command to compile the source file into a bytecode file
with a .class extension.

javac [Link]

This command generates a [Link] file.

Java Virtual Machine (JVM)


The Java Virtual Machine (JVM) is a virtual machine that enables the execution of Java bytecode on any
platform. It provides platform independence by abstracting the underlying hardware and operating
system.

Key Components of the JVM:

1. Class Loader: Loads the .class files into memory.


2. Bytecode Verifier: Ensures that the bytecode is valid and does not violate any security
constraints.
3. Interpreter: Executes the bytecode instructions.
4. Just-In-Time (JIT) Compiler: Converts bytecode into native machine code for better
performance.
5. Garbage Collector: Manages memory by automatically reclaiming memory occupied by objects
that are no longer in use.

Structures in Java Programs


Defining a class in Java: A blueprint for creating objects, defining fields and methods. Syntax:

Creating Objects: An instance of a class with its own state and behavior. Syntax

Constructors: A constructor is a special method that is called when an object is instantiated. Its primary
purpose is to initialize the newly created object. Constructors have the same name as the class and do
not have a return type.

Types of Constructors:

• Default Constructor: Provided by the compiler if no constructors are defined. It initializes objects
with default values.
• Parameterized Constructor: Allows initializing objects with specific values.
Methods/Functions: Methods are blocks of code that perform a specific task and can be invoked to
execute that task. They may return a value or be void (return nothing).

Access Specifier: It defines the scope of a class, constructor, method, or field. The main access specifiers
in Java are:

• public: Accessible from any other class.


• private: Accessible only within the class it is defined.
• protected: Accessible within the same package and subclasses.
• default (no keyword): Accessible only within the same package.
Static Members and Methods

Static Members:

• It declared with the static keyword.


• It belongs to the class rather than any instance.
• It is shared among all instances of the class.

Static Methods:

• It can be called without creating an instance of the class.


• It cannot access non-static fields or methods directly.

Comments: Comments are used to annotate the code and are not executed by the compiler. They help
in making the code more understandable.

Types of Comments:

• Single-line Comments: Use // to comment a single line.


• Multi-line Comments: Use /* ... */ to comment multiple lines.

Control Flow in Java


Control flow statements in Java determine the order in which the statements are executed. They include
conditional statements, loops, and branching statements.

1. if Statement: Executes a block of code if its condition evaluates to true.

if (condition) {

// code to be executed if condition is true

2. if-else Statement: Executes one block of code if its condition evaluates to true, otherwise
executes another block.
if (condition) {

// code to be executed if condition is true

}else {

// code to be executed if condition is false

3. else-if Ladder: Tests multiple conditions sequentially.


if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if both conditions are false
}
4. switch Statement: It selects one of many code blocks to execute based on the value of an
expression.

Loops

1. for Loop: Repeats a block of code a specified number of times.

for (initialization; condition; update) {

// code to be executed

2. while Loop: Repeats a block of code as long as its condition evaluates to true.

while (condition) {

// code to be executed

3. do-while Loop: Similar to the while loop, but it executes the block of code at least once
before testing the condition.

do {

// code to be executed
} while (condition);

Branching Statements

• break Statement: It exits from the loop or switch statement. They do not work for functions or
constructors.

for (int i = 0; i < 10; i++) {

if (i == 5) {

break;

[Link](i);

• continue Statement: It skips the current iteration of the loop and proceeds to the next iteration.
They do not work for methods.

for (int i = 0; i < 10; i++) {

if (i == 5) {

continue;

[Link](i);

• return Statement: Exits from the current method and optionally returns a value.

public int add(int a, int b) {

return a + b;

Packages in Java
A package is a namespace that organizes a set of related classes and interfaces. Packages help avoid
name conflicts and can control access to classes.

Defining a Package: To define a package, use the package keyword at the top of your Java source file.
Importing a Package: To use classes or interfaces from other packages, you need to import them using
the import statement.

API (Application Programming Interface) in Java


An API in Java refers to a set of classes and interfaces that provide a way to interact with the Java
platform and other external services or libraries.

Java Standard API: The Java Standard API (or Java Standard Library) provides a comprehensive set of
built-in classes and interfaces for performing common tasks, such as:

1. [Link]: Fundamental classes (e.g., String, Math, System).


2. [Link]: Utility classes (e.g., ArrayList, HashMap, Date).
3. [Link]: Input and output classes (e.g., File, InputStream, OutputStream).
4. [Link]: New I/O classes (e.g., Buffer, Channel).
5. [Link]: Networking classes (e.g., Socket, URL).
6. [Link]: Database access classes (e.g., Connection, Statement).
7. [Link]: GUI components (e.g., JFrame, JButton).

Using Java Standard API: To use a class from the Java Standard API, import it using the import
statement and then create objects or call static methods as needed.

You might also like