0% found this document useful (0 votes)
30 views

Java Unit-1

ITS JAVA notes for basic

Uploaded by

tvrssanjeev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Java Unit-1

ITS JAVA notes for basic

Uploaded by

tvrssanjeev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Java Unit-1

Importance of Java:
1.Platform Independence: Java's most critical features is its "write once, run anywhere" capability.
Java code can be executed on any platform that has a Java Virtual Machine (JVM).
This platform independence allows developers to create applications that can be used on various
operating systems without modification, making it highly versatile and accessible.

2.Object-Oriented Programming (OOP): Java is an object-oriented programming language, which


means it allows developers to model real-world entities and their interactions easily. OOP promotes
code reusability, maintainability, and scalability, making it an ideal choice for building complex
applications and systems.

3.Rich Standard Library: Java comes with a comprehensive standard library that offers a wide range
of pre-built classes and methods(functions declared within a class).
This library simplifies common programming tasks, such as file handling, networking, and data
manipulation, saving developers time and effort in coding from scratch.

4.Robust and Secure: Java was designed with a strong emphasis on security and robustness. It
includes features like bytecode verification, automatic memory management (garbage collection),
and exception handling,preventing security vulnerabilities and ensure stable and error-free code
execution.

5.Community and Ecosystem: Java has a massive and active developer community with a lot of
resources, tutorials, and documentation available online.
Java ecosystem is rich in tools, frameworks, and libraries that facilitate rapid development, making it
easier for developers to build structured and feature-rich applications.

Java Environment
Java's environment refers to the set of software tools and components that enable the development
and execution of Java applications.It provides the necessary infrastructure for writing, compiling,
deploying, and running Java programs.It consists of the following key components:

1. Java Development Kit (JDK): The JDK is a crucial part of the Java environment and is essential for
Java application development. It includes the following components:

 Java Compiler (javac): The Java compiler translates human-readable Java source code (with
a .java extension) into platform-independent Java bytecode (with a .class extension) that the
Java Virtual Machine (JVM) can understand.

 Java Runtime Environment (JRE): The JRE is responsible for executing Java applications. It
includes the JVM and a set of core libraries required for running Java programs.

 Development Tools: The JDK provides various development tools, including the Java Debugger
(jdb), Java Archive Tool (jar), and JavaDoc for generating documentation from source code
comments. These tools aid in the development and packaging of Java applications.

2. Java Virtual Machine (JVM): JVM stands for Java Virtual Machine. It is an essential component of
the Java Runtime Environment (JRE) that allows Java bytecode to be executed on any platform,
making Java a platform-independent language ("write once, run anywhere").
JVM acts as an interpreter for Java bytecode, which is the compiled output of Java source code.
JVM provides several features critical to Java's security and memory management, such as garbage
collection, bytecode verification, and security managers.
It also ensures that Java applications run in a protected environment, preventing unauthorized access
to system resources and ensuring the safety and stability of the runtime environment.

3. Java Standard Library: Java standard library is a collection of classes and packages that provide
core functionalities to Java applications. The standard library includes packages for I/O operations,
data structures, networking,etc.
Developers can leverage these pre-built classes to accelerate development and maintain code
consistency.

4. Java Application Programming Interface (API): The Java API is a set of rules and protocols that
allow different components of Java applications to interact with each other. It defines the classes,
interfaces, methods, and their functionalities that developers can use to build their applications.

5. Integrated Development Environments (IDEs): IDEs play a significant role in the development
process. IDEs like Eclipse, IntelliJ IDEA, and NetBeans provide advanced features such as code editors
with auto-completion, debugging tools, project management, and integration with version control
systems.
IDEs enhance developers' productivity and make it easier to build complex Java applications.

Note: Current JDK version: 20.0.2

Various Java Editions


Java comes in several editions, each tailored to meet specific development needs and application
domains. The major editions of Java are:

1. Java 2 Standard Edition (Java2SE): Java SE is the core platform that provides the fundamental
tools and libraries for developing general-purpose Java applications.
It includes the Java Development Kit (JDK) and the Java Runtime Environment (JRE).
Java SE is used for developing desktop applications, web applications, and command-line utilities.

2. Java 2 Enterprise Edition (Java2EE): Java EE is designed for developing enterprise-level


applications.
It builds upon Java SE and adds additional APIs and specifications for building distributed, scalable,
and robust applications.
Java EE includes technologies like Servlets, JavaServer Pages (JSP), Enterprise JavaBeans (EJB), Java
Persistence API (JPA), and Java Messaging Service (JMS).

3. Java 2 Micro Edition (Java3ME): Java ME is a lightweight edition of Java designed for developing
applications on resource-constrained devices such as mobile phones, embedded systems, and IoT
(Internet of Things) devices.
It provides a smaller footprint of the Java runtime and a limited set of APIs optimized for small-scale
applications.

From Code to Output


 Source Code:The set of instructions in a program.The set of instructions in a program.
 Compile:Translate a program from one language to another.
 Byte Code:The Java compiler converts your code into a format named byte code that runs on
many computer types.
 Output:The messages printed to the user by a program.

How Java is different from C


1. Programming Paradigm: C is a structured-oriented language, which focuses on breaking down
programs into smaller functions and modules, WHILE Java is an object-oriented language, which
revolves around creating and interacting with objects that encapsulate data and behavior.

2. Pointers: C supports explicit pointers that allow direct manipulation of memory addresses,
WHEREAS Java abstracts away pointers and provides automatic memory management through
references, ensuring a safer and more secure memory management model.

3. Preprocessor: In C, the preprocessor allows the use of directives like #define and #include for
macros and header file inclusion.
In Java, there is no preprocessor, and the language itself provides alternative mechanisms for
constants and code organization, like final variables and packages.

4. Data Types: C includes structures, unions, and enum data types, which allow developers to create
custom composite data types and enumerate constants.
Java, on the other hand, does not have these explicit data types, as it relies on class definitions and
object-oriented principles for data organization.

5. Missing Keywords: Java omits certain keywords found in C, such as goto, sizeof, and typedef, as
these keywords can lead to complex and less maintainable code.
Java promotes structured and object-oriented programming practices, which encourage better code
organization and readability.

How Java is different from C++


1. No Pointers and Memory Access: Unlike C++, Java does not support pointers, which eliminates
unauthorized access to memory locations, making it a safer language with fewer memory-related
issues.

2. No Structures, Unions, and Enum Data Types: Java does not include structures, unions, and enums,
simplifying the language and promoting object-oriented programming practices.

3. No Operator Overloading: Java does not support operator overloading, ensuring a consistent and
predictable behavior of operators across different data types.

4. No Preprocessor: Java eliminates the preprocessor entirely, reducing complexity and ensuring a
cleaner codebase without conditional compilation.
5. No Automatic Type Conversions with Loss of Precision: Java does not allow automatic type
conversions that may result in loss of precision, reducing the risk of unintended data loss and
ensuring more explicit type casting.

OOP:Object-Oriented Programing
Object-Oriented Programming (OOP): is a programming paradigm that organizes code and data into
reusable units called "objects."
Each object represents a specific entity or thing with its own attributes (data) and behaviors
(functions or methods).
OOP is all about modeling real-world entities and their interactions in a way that makes it easier to
understand and manage complex systems.
Example: A car is an object that has various attributes and behaviors.In OOP, we would represent a
car as an object with its properties (attributes) and actions (behaviors)
Where:Properties:Colour,Year of Manufacture,Model,etc.
Actions:Accelarate,Brake,Start the engine,etc.

OOP Concepts:

 Object :
 An object is a fundamental unit in Object-Oriented Programming (OOP) that represents
a real-world entity with its attributes (data) and behaviors (methods).
 Objects are instances of classes, and they encapsulate data and methods specific to
that entity, making it easier to model complex systems and interact with them.
 For example, in a banking application, a "Customer" object could represent an
individual customer with attributes like name, account number, and balance, and
behaviors like deposit and withdraw.

 Class:
 A class is a blueprint or template for creating objects. It defines the properties (attributes) and
behaviors (methods) that the objects of that class will possess.
 Classes act as a blueprint from which we can create multiple objects with the same structure but
different data values.
 For example, a "Car" class could define attributes like color, make, model, and year, and
methods like startEngine, accelerate, and brake. From this class, we can create various car
objects, each representing a specific car with its unique attributes and behaviors.

 Inheritance:
 Inheritance is a mechanism in OOP where one class (subclass or derived class) inherits the
properties and behaviors of another class (superclass or base class).
 It allows a subclass to reuse the code from its superclass, promoting code reusability and
reducing duplication.
 For example, a "Truck" class can inherit from the "Car" class, inheriting all the attributes and
methods of the "Car" class while adding truck-specific attributes and methods.

 Polymorphism:
 Polymorphism allows objects of different classes to be treated as objects of a common
superclass. It allows a single interface to represent different types of objects.
 There are two types of polymorphism: compile-time polymorphism (method overloading) and
runtime polymorphism (method overriding).
 Method Overloading: Creating multiple methods in the same class with the same name but
different parameters.
 Method Overriding: Providing a specific implementation for a method in a subclass that is
already defined in its superclass.
 For example, in a shape hierarchy, both circles(sub-class) and squares(sub-class) can be treated
as shapes(super-class), and a method like "calculateArea" can be defined in the superclass.
Subclasses can then override this method to calculate the area based on their specific shapes.

 Abstraction:
 Abstraction is the process of simplifying complex systems by focusing on the essential features
while hiding unnecessary details.
 In OOP, abstraction is achieved through abstract classes and interfaces, which define the
structure and contract of classes without providing the implementation.
 For example, a "Shape" abstract class can define the "calculateArea" method without specifying
how each shape calculates its area. Subclasses will provide the implementation for their specific
shapes.

 Encapsulation:
 Encapsulation is the bundling of data (attributes) and methods (behaviors) together within
a class, hiding the internal details and exposing only the necessary interfaces to interact
with the object.
 It helps achieve data protection, as access to the data is controlled through methods,
ensuring data integrity and security.
 For example, a "BankAccount" class may have private attributes like accountNumber and
balance, with public methods like deposit and withdraw to interact with and modify these
attributes securely.

Types of Java Program:

The distinction between standalone applications and applets is based on their deployment and
execution scenarios. Both types of programs are written in Java and use similar syntax and language
features.

Java Standalone Applications:


Standalone applications in Java are traditional programs that run independently on a user's computer
or server.
They are not dependent on web browsers or internet connectivity to execute.
Java standalone applications are launched and executed like any other desktop application.

Examples: text editors, media players, desktop games, and various utility programs. These
applications are built using Java's core libraries and may also use additional libraries and frameworks
for specific functionalities.

Java Applets:
Java applets are small Java programs designed to run within a web browser.
They are embedded in web pages and executed on the client-side when a user visits a webpage
containing the applet.

Applets run in a restricted environment known as the "sandbox" to prevent malicious actions and
ensure security.
They have limited access to system resources on the user's computer to prevent any potential harm.
Java Program Structure

 Documentation Section:To mention the aim or content of the program.

 Package Statement:Packages are used to organize classes into logical groups


The package statement specifies the package name to which the class belongs.

 Import Statement:Import statements to specify the classes that need to be imported into
the current program.

 Interface Statement:An interface defines a contract or set of rules that classes must follow if
they implement that interface

 Class Definition:The class declaration includes the keyword "class" followed by the class
name, opening and closing curly braces, and the class's body that contains its properties
(attributes) and behaviors (methods).

 Main Method Definition:It is a special method that acts as the starting point of the program.

Structure of a Java Program


class class-name
{
public static void main(String args[])
{
statement1;
statement2;

}
}
Compiling and Running a Program
Compiling(program) : is the process of translating source code written in a particular programming
language into computer-readable machine code that can be executed.
Syntax:
javac <filename>.java
This command will produce a file ‘helloworld.class’, which is used for running the program with the
command ‘java’.

Running (program) : is the process of executing program on a computer.


Syntax:
java <filename>

Defining a Class in Java


Syntax:

class <classname>
{
type instance variable 1;
type instance variable 2;
type instance variable n;
}

Note: The variables, defined within a class are called instance variable

Important Keywords:
1. public:
public is an access specifier [controls accessibility of class members (variables, methods, and inner
classes)] in Java that allows class members to be accessible from any other class.
When a class member is declared as public, it can be accessed and used by code defined outside the
class in which it is declared, enabling other classes to interact with and utilize the public members.

2. private:
private is an access specifier in Java that restricts the visibility of class members to only within the
same class where they are declared. Private members cannot be accessed from other classes.
By declaring a class member as private, ensures that the implementation details of the class are
hidden and cannot be directly accessed or modified from external code.

3. protected:
Protected represents a visibility level that allows access to members (variables or methods) within
the same class, within subclasses (classes that inherit from the class where the member is declared),
and also within the same package
4. static:
static is a keyword in Java used to create class members(variable/method) that are shared among all
instances(instance variables and methods) of the class.
When a method or variable is declared as static, it can be accessed without creating an instance of
the class.
For example: the main() method in Java is typically declared as static, allowing it to be called by the
Java Virtual Machine (JVM) without creating an object of the class containing main().
5. main:
main is a special method in Java that serves as the entry point for the program's execution. It is the
starting point when a Java program is run, and the JVM looks for the main method to begin executing
the code.
The main method must have the exact signature: public static void main(String[] args). It takes a
single argument of type: String array (String[]), which allows command-line arguments(values passed
from cmd or terminal) to be passed to the program.

6. void:
void is a return type in Java used with methods to indicate that the method does not return any
value. Methods declared with void do not have a return statement or return a value.
For example, the main method is declared with a return type of void because it does not need to
return any value.

7. String args[]:
String args[] is the parameter declaration for the main method. It allows the program to accept
command-line arguments when the program is run from the command line.
Command-line arguments are parameters or values that are provided to a program when it is run
from the command line or terminal.
Command-line arguments are passed to the Java program as an array of strings, where each element
in the array represents an argument passed to the program when it is launched.

8. System:
System is a predefined class in Java that provides access to various system-related operations and
resources.
The System class is often used to access standard input, output, and error streams, perform memory
management, interact with the environment, and more.

9. out:
out is a static variable of the System class that represents the standard output stream(default
destination for output messages).
It is an instance of the PrintStream class.
By using System.out, we can access the standard output stream and use methods like println() to print
text and data to the console.

10. println:
println is a method of the PrintStream class used to print text or data to the standard output stream
with a newline character at the end.
It stands for "print line."
When we call System.out.println(), the specified text or data is displayed on the console, and a
newline is automatically added after the output, ensuring the next output appears on a new line.

Note: // is used for comments

Characterstics of Java
1) Simple – Java's syntax is straightforward and easy to understand for developers.
2) Object-oriented – Java follows the object-oriented programming paradigm, organizing
software design around objects and their interactions.
3) Platform independent – Java code can run on multiple platforms without modification due to
its "write once, run anywhere" capability.
4) Distributed – Java supports distributed computing, allowing collaboration among multiple
computers over a network.
5) Robust – Java is reliable and strong thanks to its compiler and interpreter, which catch errors
early in the development process.
6) Architectural neutral – Java does not have implementation-dependent aspects, making it
compatible with various architectures.
7) Portable – Java programs are architecture-independent and can be easily moved from one
system to another.
8) High performance – Java achieves remarkable performance and efficiency due to its bytecode
being close to machine code.
9) Multithreaded – Java supports multithreading, enabling the execution of multiple parts of a
program simultaneously to optimize CPU efficiency.
10) Dynamic – Java is considered dynamic as actions can occur during runtime due to its bytecode
nature.
11) Secure – Java ensures security through secure compilation and interpretation mechanisms,
reducing the risk of malicious code execution.

Data Types in Java

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes,Interfaces and Arrays

Primitive data types:

1. Integer:used for storing integer values.


 There are four java integer types
 Supports signed integers (positive or negative)
2. Float:Used for representing numbers with a decimal part
 There are two floating point types

3. Character:Used for representing individual characters


 Char type has 16 bits of precision, unsigned.
 We use ‘’ for character.While for strings “” is used.

4. Boolean:Can have one of two values – true or false


 Boolean is not a number nor can it be treated as one
 All tests of Boolean variables should test for true or false

5. String:represents a sequence of characters

Variable
A variable is a named storage location in a computer's memory that holds a value. It allows you to
store and manipulate data during the execution of a program.
They have a name, a type and a value
Syntax for declaration:
datatype <variable name>;
Example:char index =’a’;
String=”Abc”
int a,b,c,sum,interest;
Rules for declaration:
1. Variable Name: The variable name can be a combination of letters (uppercase or lowercase),
digits, and the underscore (_) character. It must start with a letter or underscore, not with a digit.
Java is case-sensitive, so variables named "myVar" and "myvar" are considered different.
2. No Reserved Keywords: You cannot use reserved keywords as variable names. For example,
"int," "double," "if," "while," etc., are reserved keywords and cannot be used as variable names.
3. No Special Characters: Variable names cannot contain special characters other than the
underscore (_). So, names like "my-var" or "my$var" are not allowed.
4. Cannot Start with a Digit: Variable names cannot begin with a digit. For instance, "1var" is not a
valid variable name.

Operators
Operators are special symbols or keywords that perform various operations on variables or values.
Operators in java include :
1) Arithmetic Operator

2) Assignment Operator
3) Increment and Decrement Operators

4) Comparison Operator

5) Logical Operator
Accesing built in functions
These built-in functions are stored in classes contain various methods that provide predefined
functionality for common tasks.
Example:
The Scanner class is part of the java.util package and is used for tasks like reading primitive data types
(integers, floating-point numbers, etc.) and strings.

Step1:Import Scanner class


import java.util.Scanner;

Step2:Create scanner object


Scanner obj = new Scanner(System.in);

Step3:Reading input using Scanner methods


int intValue = scanner.nextInt();
double doubleValue = scanner.nextDouble();
String stringValue = scanner.nextLine();
Type Casting
Type casting in Java is the process of converting a value from one data type to another.
Syntax:
Type variable1=(type) variable 2;

Example:int m=(byte) n;
char abc=(char) intValue;

Operator Presidence
Operator precedence in Java defines the order in which different operators are evaluated when an
expression contains multiple operators.
Decision Making Statements:
1) Simple if
We use a simple if statement when you want to execute a block of code only if a single condition is
true. This is the most basic form of decision-making.

2) If else
We use an if-else statement when you want to execute one block of code if a condition is true, and
another block of code if the condition is false.

3) Nested if
Nested if statements is used when you want to check multiple conditions in a sequence. Each if
statement is nested inside another, and the inner conditions are evaluated only if the outer
conditions are true.
4) Else if ladder
Else if ladder is used when you have multiple conditions to check, and you want to execute a specific
block of code based on the first condition that is true. This is useful when you have a series of
mutually exclusive options.
5) Switch case
Switch statement when you have a single variable or expression that you want to compare against
multiple possible values. It provides a neat way to handle multiple cases without writing nested if-else
statements.Switch is more efficient than Else if ladder
Looping Statements:
Looping statements in Java are used to repeat a block of code multiple times. Each type of looping
statement serves a specific purpose, and you choose the appropriate one based on the conditions
1) For loop
Use a for loop when you know the exact number of times you want to repeat a block of code. It's
especially useful when you have a well-defined starting point, ending point, and increment or
decrement value.
2) While loop
Use a while loop when you want to repeat a block of code as long as a certain condition is true. The
condition is checked before each iteration, and the loop continues as long as the condition remains
true.
Also known as “entry-level loop”.

3) Do while loop
Use a do-while loop when you want to execute a block of code at least once, and then repeat it as
long as a certain condition is true. The condition is checked after each iteration.
Also known as “exist-level loop”.

Class,Objects and Method


Class Declaration: A class declaration gives the properties (fields) and behaviors (methods)
that objects of the class will have.

class <classname>
{
type instance variable 1;
type instance variable 2;
………………..
}

Eg:
Class Box
{
Double height;
Double breadth;
Double length;
}

Method Declaration:A method declaration includes the method's access specifier, return
type, name, parameters, and method body.

return type <method name>(parameter_list)


{
Method body
}

Eg:
void area_sq(int l)
{
Int L=l;
Area=l*l;
}
Object Creation and Declaration:Usually to use the properties and methods
defined in a class, you need to create objects of that class.Object creation involves invoking a class's
constructor using the new keyword.
Eg:
Box mybox = new Box();

Constructors Vs Method

Aspect Methods Constructors


Purpose Perform specific actions or Initialize object state during
operations. creation
Name Can have any name. Must have the same name as
the class.
Return Type Can have a return type No return type (not even void).
(including void).
Invocation Called explicitly using the Automatically invoked upon
method name. object creation
Explicit call Can be called multiple times in Constructors are called only
the same object or between once per object creation.
different objects.
Default and Parametrized Constructor
Refer to slides 80,81 in JAVA_Unit.pptx (code)

Static Variables and Static methods


Class-Level: Static variables (or class variables) belong to the class itself, not to individual objects of
the class. Similarly, static methods are methods that operate at the class level, not on specific
instances of the class. This means you don't need to create an object to access them,they can be
access them directly using the class name.

Shared Among All Instances:If we change the value of a static variable in one instance, it will affect
the variable's value for all other instances of that class. This makes static variables useful for storing
data that should be common across all instances, such as constants or shared resources.

Memory Efficiency and Utility: Static variables and methods are memory-efficient because they are
created and allocated only once when the class is loaded by the JVM.

Refer to slides 83,84 in JAVA_Unit.pptx (For code)

“this” keyword
The this keyword in Java is used to refer to the current instance of the class in which it is used.Mainly,
to eliminate the confusion between class attributes and parameters with the same name
Use Case:

Reference to Current Instance: The this keyword in Java is used as a reference to the current instance
of the class in which it is used. It allows you to access instance-specific members and methods within
the class.

Disambiguation: this is primarily used to distinguish between instance variables and local variables
(such as method parameters) with the same name, ensuring that you're working with the correct
variable or method.

Slide 87 (For Code)

Method Vs Constructor Overloading


Aspect Method Overloading Constructor Overloading
Purpose Allows a class to have multiple Enables a class to have multiple
methods with the same name constructors with varying
but different parameter lists, parameter lists for flexible object
enabling method versatility. initialization.
Name Methods must have the same Constructors must have the same
name but different parameter name as the class and different
lists (number or type of parameter lists.
parameters).
Return Type Method overloading is based on Constructor overloading is based
the method name and solely on the parameter lists.
parameter lists, not on the
return type.
Inheritance Methods can be inherited and Constructors are inherited but
overridden by subclasses. cannot be overridden; only
constructors of the same name can
be called.
Use Case Useful for providing multiple Useful for initializing objects in
ways to perform the same various ways, such as with
action, often with different different initial values or
input types. configurations.

Slide 88,89,91(For Code)

Java Libraries
 java.lang: Basic language utilities, automatically imported, includes fundamental classes like
String and Object.

 java.util: Provides utility classes like ArrayList and HashMap for working with data structures and
collections,contains Scanner as well.

 java.io: Used for input and output operations, including reading and writing files.

 java.net: Deals with networking, allowing Java applications to communicate over the internet.

 java.awt: Provides tools for creating graphical user interfaces (GUIs) in desktop applications.

 java.applet: Used for creating applets, which are small Java programs that can be embedded in
web pages.

Arrays
An array is a data structure that allows you to store a group of related or contiguous data items under
a single common name.
Each item in an array is identified by a number starting from 0.

Declaration:
Syntax: datatype arrayname [ ]; OR datatype[ ] arrayname;
int[ ] numbers; OR int numbers[ ];

Initialization:
 To create an array in memory, use the new operator like this:
int[] scores = new int[5];

 You can set values when you declare an array:


int[] primes = {2, 3, 5, 7, 11};

Array Length:
To check how many items are in an array, use the length property:
int size = ages.length;

Slide 96 (For Code)

2D Arrays
It's a data structure that allows you to organize data in a grid or matrix format

Syntax:
type arrayname [ row size] [col size ] ;
int matrix[3][3]
OR
arrayname = new type [row size] [col size];
matrix = new int[3][3];

Initialization:
int[ ][ ] matrix = {{1, 2, 3},{4, 5, 6},{7, 8, 9}};

You might also like