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

Java Unit1 Introduction

The document provides an introduction to Java programming, detailing its history, core components, features, and object-oriented programming concepts. It explains how Java works, including the compilation and execution process, and covers data types, variables, and operators. Additionally, it highlights the benefits and applications of object-oriented programming in various fields.
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 views38 pages

Java Unit1 Introduction

The document provides an introduction to Java programming, detailing its history, core components, features, and object-oriented programming concepts. It explains how Java works, including the compilation and execution process, and covers data types, variables, and operators. Additionally, it highlights the benefits and applications of object-oriented programming in various fields.
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 PROGRAMMING

UNIT 1

INTRODUCTION
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 a 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 name from Oak
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.

How Java Works

1. Write Code

The developer writes the code in the Java programming language using a text file.

 File extension: .java

2. Compile

The program is compiled using javac, which is part of the Java Development Kit (JDK).

 It translates the source code into bytecode


 Bytecode is stored in a .class file

Run

The Java Virtual Machine (JVM) interprets and executes the bytecode on the target device.

 It converts bytecode into machine-readable code


 It may use a Just-In-Time (JIT) compiler for faster execution

Core Components

1. JVM (Java Virtual Machine)

 It is the engine that runs Java programs


 Converts bytecode into machine-readable code

2. JRE (Java Runtime Environment)

 Includes the JVM, libraries, and other components


 Required to run Java applications.

Department of BCA, AIBM Page 1


JAVA PROGRAMMING

3. JDK (Java Development Kit)

 Full kit for developing Java applications


 Includes:
o JRE
o Development tools like:
 Compiler (javac)
 Debugger

Features of Java
Simple

Java is easy to learn, with a syntax that is simple, clean, and easy to understand.

Object-Oriented

Java is an object-oriented programming language where everything is an object. Object-


oriented programming means that we organize our software as a combination of various types
of objects that incorporate both data and behavior.
The basic concepts of OOP are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Portable

Java's portability allows programs to run on various platforms without modification. This is
achievable because Java code is compiled into bytecode, which is independent of the
underlying hardware and operating system.

Platform Independent

Java is platform-independent because it differs from other languages like C, C++, etc., which
are compiled into platform-specific machines. In contrast, Java is a write once, run
anywhere(WORA) language. A platform refers to the hardware or software environment in
which a program runs.

There are two types of platforms: software-based and hardware-based. Java offers a software-
based platform.

Secured

Java is renowned for its security. With Java, we can create virus-free systems. Java is secure
because:

Department of BCA, AIBM Page 2


JAVA PROGRAMMING

 No explicit pointer

 Java Programs run inside a virtual machine sandbox

Robust

The English meaning of Robust is strong. Java is robust for the following reasons:

o It employs strong memory management.

o There is a deficiency of pointers that prevent security issues.

o Java offers automatic garbage collection.

o Java includes exception handling and type checking mechanisms.

Interpreted

Java's interpreted feature means that Java code is not directly converted into machine code by
a compiler. Instead, first, it compiled into bytecode, then executed by the JVM through
an interpreter. It allows Java to be platform-independent, meaning the same bytecode can
run on any system with a JVM.

High performance: Java is a high-performance programming language.

Multithreaded: A thread is like a separate program that executes concurrently.

We can write Java programs to handle many tasks simultaneously by defining multiple threads.

Distributed

Java is designed for distribution, allowing users to develop distributed applications effectively.

Dynamic

Java is a dynamic language that supports the on-demand loading of classes.

Java supports dynamic compilation and automatic memory management, including garbage
collection.

Basic Structure of a Java Program


public class Main
{
public static void main(String[] args)
{
[Link]("Hello, World!"); // Print a message to the console

Department of BCA, AIBM Page 3


JAVA PROGRAMMING

}}

Explanation

1. class HelloWorld
o Every Java program must have a class.
o HelloWorld is the class name (same as file name: [Link]).
2. public static void main(String[] args)
o This is the main method.
o Program starts execution from here.
o public → accessible to JVM
o static → no object needed
o void → no return value
3. [Link]("Hello, World!");
o Used to print output on the screen.
4. { } Curly Braces
o They define the start and end of class and methods.

Object oriented concepts(OOPs) and paradigm


Object-oriented programming (OOPs) is a programming paradigm that uses objects to structure
code. The key concepts of OOPs include class, Object, encapsulation, inheritance,
polymorphism, and abstraction.

Class
Class is a logical entity. A class can also be defined as a blueprint from which we can create
an individual object. Class does not consume any space.
Example:
A Student class defines what a student has (name, rollNo) and what a student does (read, write).
class Student
{
int rollNo;
String name;
void study()
{
[Link]("Student is studying");
}
}

Object
 Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc.
 It can be physical or logical.
 An Object can be defined as an instance of a class.
 It contains an address and takes up some space in memory.
 Objects can communicate without knowing the details of each other's data or code.

Example:
Student Ram is an object of the Student class.
Student s1 = new Student();
Department of BCA, AIBM Page 4
JAVA PROGRAMMING

[Link] = 1;
[Link] = "Ram";
[Link]();

Encapsulation
means binding data and methods together and protecting data.
Encapsulation is important for data security.

class BankAccount
{
private int balance = 1000;
public void showBalance()
{
[Link](balance);
}
}

Inheritance
Inheritance means one class acquiring properties of another class.

Child class uses parent class features.

class Animal

{
void eat()
{
[Link]("Animal eats");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Dog barks");

Polymorphism
Polymorphism means one method having many forms.

Method Overloading (Compile-time)


class Add

int sum(int a, int b)


Department of BCA, AIBM Page 5
JAVA PROGRAMMING

return a + b;

int sum(int a, int b, int c)

return a + b + c;

Method Overriding (Run-time)

class Animal {

void sound() {

[Link]("Animal makes sound");

class Dog extends Animal {

void sound() {

[Link]("Dog barks");

Abstraction

Hiding internal implementation and showing functionality only to the user is known as
abstraction.
For example, in phone calls, we do not know the internal processing. In Java, we use abstract
classes and interfaces to achieve abstraction

Example

abstract class Vehicle {

Department of BCA, AIBM Page 6


JAVA PROGRAMMING

abstract void start();

class Bike extends Vehicle {

void start() {

[Link]("Bike starts with kick");

}
Dynamic Binding
Dynamic Binding means the method call is resolved at runtime not at compile time.
 The system is decides which method to execute based on the actual object type. Even
if the reference is of a parent class.
 It associated with polymorphism and Inheritance.
 It is mainly used in mehod overriding and support Runtime Polymorphism.

Example

class Animal

void sound()

[Link]("Animal sound");

class Dog extends Animal

void sound()

[Link]("Dog barks");

Department of BCA, AIBM Page 7


JAVA PROGRAMMING

Animal a = new Dog();

[Link](); // Dog barks (decided at runtime)

Message Passing
An object –oriented program consists of a set of objects that communicate with each other.
The process of programming in an Object –Oriented language.
Involves the following basic steps
1. Creating classes that define objects and their behaviour.
2. Creating object from class definition.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same
way as people pass message to one another.

Example

class Student

void study()

[Link]("Student is studying");

Student s = new Student();

[Link](); // Sending message to object

Department of BCA, AIBM Page 8


JAVA PROGRAMMING

Benefits OOps

 Reusability
Code can be reused using inheritance, reducing duplication.

 Modularity
Program is divided into small parts (classes and objects), making it easy to manage.

 Encapsulation (Data Hiding)


Data and methods are combined in a class and protected from outside access.

 Abstraction
Hides unnecessary details and shows only important features.

 Flexibility (Polymorphism)
One method can perform different tasks.

 Maintainability
Easy to modify and update the program.

 Security
Data is secure due to access control (private, public).

 Reduced Code Complexity


Simplifies large programs by dividing into smaller modules.

 Easy Debugging
Errors can be easily found and fixed.

 Scalability
Easy to expand the program in future.

Applications Of OOPs

 Real-Time Systems
Used in systems like traffic control, banking, and telecom.

 Simulation and Modeling


Used to create models like flight simulation and games.

 GUI Applications
Used in designing user interfaces like buttons, windows, and menus.

 Web Applications
Used in developing websites and web services.

 Mobile Applications
Used in Android and other mobile app development.

Department of BCA, AIBM Page 9


JAVA PROGRAMMING

 Game Development
Used to design characters, objects, and game logic.

 Database Applications
Used in managing and accessing databases.

 Distributed Systems
Used in client-server and network-based applications.

 Artificial Intelligence
Used in AI systems and machine learning programs.

 Software Development
Used in large-scale enterprise applications.

Data Types
In Java, data types are divided into two main categories:

1. Primitive Data Types

2. Non-Primitive (Reference) Data Types

1. Primitive Data Types


These are the basic building blocks for data manipulation in Java. They are predefined by the
language and are not objects.
Data Default
Size (in bits) Description
Type Value
byte 8 0 Stores small integers (-128 to 127).
short 16 0 Stores integers (-32,768 to 32,767).
int 32 0 Stores integers (-2³¹ to 2³¹-1).
long 64 0L Stores large integers (-2⁶³ to 2⁶³-1).
Stores fractional numbers with up to 7 decimal
float 32 0.0f
digits of precision.
Stores fractional numbers with up to 16 decimal
double 64 0.0d
digits of precision.
char 16 '\u0000' Stores a single character (Unicode, 0 to 65,535).
1 (not precisely
Boolean false Stores true or false.
defined)

2. Non-Primitive (Reference) Data Types


These include classes, interfaces, arrays, and strings. Unlike primitive types, these types are
created by the programmer and are used to store complex objects.

Department of BCA, AIBM Page 10


JAVA PROGRAMMING

Examples:

• String: A sequence of characters (e.g., "Hello"). Strings are immutable objects in Java.
• Arrays: Used to store multiple values of the same type (e.g., int[] numbers = {1,
2, 3};).
• Classes: User-defined types (e.g., class Person { ... }).
• Interfaces: Abstract types used to define a contract that classes can implement.

Variable
A variable is a name given to a memory location used to store data. It can change n number
of times during execution.
1. Variable declaration Syntax:
Datatype variable_name;

Identifier name
Example: int a;
2. Variable Identification Syntax:
Variable_name=Value;
Example: a=10;

3. Variable Utilization
Syntax:
[Link](a);

4. Variable Re-initialization
int b=90; b=20;
[Link](b);

5. Coping the value from one variable toanother


int a=90;
int b=a;
[Link](a);
[Link](b);
Example for variable
class Sample
{
public static void main(String[] args)
{
int a; //variable declaration
a=10; //variable initialization
[Link](a); //variable utilization
}

Department of BCA, AIBM Page 11


JAVA PROGRAMMING

}
Types of Variables
They are 3 types
[Link] Variable
2. Instance Variable
3. Static Variable
[Link] Variable
Local variable is a variable which can be declared inside the method is called local variable.
class Example
{
public static void main(String[] args)
{
int a = 10; // local variable
[Link](a);
}
}
2. Instance Variable
It is a variable which can be declared outside the method and inside the class it is called
instance variable.

class Sample
{
int a=60; // instance variable
public static void main(String[] args)
{
[Link](a);
}
}
3. Static Variable
Static variables are variables declared using the static keyword inside a class but outside any
method.
class College
Department of BCA, AIBM Page 12
JAVA PROGRAMMING

{
static String collegeName = "ABC College"; // static variable
public static void main(String[] args)
{
[Link](collegeName);
}
}

Operators

Operators are symbols used to perform operations on variables and values.

1. Arithmetic Operators
Used for mathematical operations.
Operator Description Example

+ Addition a+b

- Subtraction a-b

* Multiplication a*b

/ Division a/b

% Modulus (remainder) a%b

2. Relational (Comparison) Operators


Used to compare two values.
Operator Description Example

== Equal to a == b

!= Not equal to a != b

> Greater than a>b

< Less than a<b

>= Greater than or equal to a >= b

Department of BCA, AIBM Page 13


JAVA PROGRAMMING

<= Less than or equal to a <= b

3. Logical Operators
Used to perform logical operations (mostly with boolean values).
Operator Description Example

&& Logical AND (short-circuit) a > 0 && b > 0

! Logical !a
NOT

4. Bitwise Operators
Operate on bits and perform bit-level operations.
Operator Description Example

& Bitwise AND a&b

` ` Bitwise OR

^ Bitwise XOR a^b

~ Bitwise Complement ~a

<< Left shift a << 2

>> Right shift a >> 2

>>> Unsigned right shift a >>> 2

5. Assignment Operators
Used to assign values to variables.
Operator Description Example

= Assign a=5

+= Add and assign a += 5

Department of BCA, AIBM Page 14


JAVA PROGRAMMING

-= Subtract and assign a -= 5

*= Multiply and assign a *= 5

/= Divide and assign a /= 5

%= Modulus and assign a %= 5

6. Unary Operators
Work with a single operand.
Operator Description Example

+ Unary plus +a

- Unary minus -a

++ Increment a++ or ++a

-- Decrement a-- or --a

! Logical NOT !a

[Link] Operator

A shorthand for if-else conditions.

Operator Description Example

?: Conditional result = (a > b) ? a : b


Operator

8. Special Operators
Used for specific functionalities.
Operator Description Example

instanceof Tests if an object is an instance of a obj instanceof String


class

Department of BCA, AIBM Page 15


JAVA PROGRAMMING

new Creates new objects new ClassName()

Control Structures
1. Selection Control Structures
Selection structures are used to make decisions in a program based on conditions.

a. if Statement
Executes a block of code if a condition is true.

Syntax:
if (condition)
{
// code to execute if condition is true
}
Example:
if (age > 18)
{
[Link]("You are eligible to vote.");
}
b. if-else Statement
Executes one block of code if the condition is true and another if it is false.
Syntax:
if (condition)
{
// code to execute if condition is true
}
else
{
// code to execute if condition is false
}
Example:
if (marks >= 50)
{
[Link]("You passed.");
}
else
{
[Link]("You failed.");
}
c. if-else-if Ladder
Tests multiple conditions sequentially.
Syntax:
if (condition1)
{
// code for condition1
}
else if (condition2)
{

Department of BCA, AIBM Page 16


JAVA PROGRAMMING

// code for condition2


}
else
{
// code if none of the conditions are true
}
Example:
if (marks >= 90)
{
[Link]("Grade: A");

}
else if (marks >= 75)
{
[Link]("Grade: B");
}
else if (marks >= 50)
{
[Link]("Grade: C");
}
else
{
[Link]("Fail");
}
d. switch Statement
Selects one of many blocks of code to execute based on a value.
Syntax:
switch (expression)
{
case value1:
// code for case value1
break;
case value2:
// code for case value2
break;
default:
// code if no cases match
}
Example:
int day = 3;
switch (day)
{
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
Department of BCA, AIBM Page 17
JAVA PROGRAMMING

break;
default:
[Link]("Invalid day");
}

2. Looping Control Structures


Looping structures are used to execute a block of code multiple times.

a. for Loop
Executes a block of code a specified number of times.

Syntax:
for (initialization; condition; update)
{
// code to execute
}
Example:
for (int i = 0; i < 5; i++)
{
[Link]("Iteration: " + i);
}
b. while Loop
Executes a block of code while a condition is true.
Syntax:
while (condition)
{
// code to execute
}
Example:
int i = 0;
while (i < 5)
{
[Link]("Iteration: " + i);
i++;
}

c. do-while Loop
Executes a block of code at least once, and then repeats while the condition is true.
Syntax:
do
{
// code to execute
}
while (condition);

Example:
int i = 0;
do
{
[Link]("Iteration: " + i);
Department of BCA, AIBM Page 18
JAVA PROGRAMMING

i++;
}
while (i < 5);

d. Enhanced for Loop (for-each)


Used to iterate over arrays or collections.
Syntax:
for (type variable : array) {
// code to execute
}

Example:
int[]
numbers = {1, 2, 3, 4, 5};
for (int num : numbers)
{
[Link](num);
}

3. Branching Control Structures


Branching allows the program to jump to another part of the code.
a. break Statement
Exits the loop or switch statement.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break;
}
[Link](i);
}
output: 0,1,2,3,4

b. continue Statement
Skips the current iteration and proceeds to the next iteration.
Example:
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
continue;
}
[Link](i);
}
output: 0,1,2,3,4,6,7,8,9

c. return Statement
Exits from the current method and optionally returns a [Link] PROGRAMMING
Example:
Department of BCA, AIBM Page 19
JAVA PROGRAMMING

public int sum(int a, int b)


{
return a + b;
}

Method Overloading
Method overloading in Java means defining more than one method with the same
name in the same class, but with different parameter lists.
The difference can be in:
 Number of parameter
 Type of parameters
 Order of parameters
The return type alone cannot be used to overload a method.

Rules of Method Overloading


A method is overloaded if:
 Same method name.
 Same class.
 Different parameters.
 There is no restrictions on access specifier, modifier and return type.
Example
class Add
{
int sum(int a, int b)
{
return a + b;
}
int sum(int a, int b, int c)
{
return a + b + c;
}
public static void main(String[] args)
{
Add obj = new Add();
[Link]([Link](10, 20));
[Link]([Link](10, 20, 30));
}
}

Java Math Class


The Java Math class is a fundamental part of the Java language's standard library, offering a
wide range of mathematical functions. It provides static methods for performing basic
arithmetic operations like addition, subtraction, multiplication, and division. Additionally, it
offers methods for more complex operations such as finding the maximum or minimum of two
numbers, raising a number to a power, and calculating logarithms and trigonometric functions.
Java Math class provides several methods to work on math calculations like min(), max(),
avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Department of BCA, AIBM Page 20


JAVA PROGRAMMING

Method Description Example Output


[Link](x) Returns square root of x [Link](25) 5.0
[Link](a, b) Returns a raised to power b [Link](2, 3) 8.0
[Link](a, b) Returns larger value [Link](10, 20) 20
[Link](a, b) Returns smaller value [Link](10, 20) 10
[Link](x) Returns absolute value [Link](-15) 15
[Link](x) Rounds to nearest integer [Link](5.6) 6
[Link](x) Rounds up to next integer [Link](4.2) 5.0
[Link](x) Rounds down to integer [Link](4.9) 4.0
[Link]() Returns random value (0.0–1.0) [Link]() 0.0–1.0
[Link](x) Returns natural logarithm [Link](10) 2.30
[Link](x) Returns sine value [Link](30) -0.988
[Link](x) Returns cosine value [Link](30) 0.154
[Link](x) Returns tangent value [Link](45) 1.61

Arrays in java
An array is a fixed-size collection of elements of the same type stored in contiguous
memory locations.
Key Characteristics of Arrays
1. Fixed Size: Once created, the size of the array cannot be changed.
2. Homogeneous Elements: All elements in an array must be of the same data type.
3. Zero-Based Indexing: Array indices start at 0 and go up to length - 1.
4. Continuous Memory Allocation: Elements are stored in contiguous memory
locations.

Declaring and Initializing Arrays


1. Declaration
To declare an array, specify the type of elements followed by square brackets.
Syntax:
dataType[] arrayName;

Examples:
int[] numbers; // Array of integers
String[] names; // Array of strings
double[] prices; // Array of doubles

2. Initialization
Use the new keyword to allocate memory for the array.
Syntax:
arrayName = new dataType[size];

Department of BCA, AIBM Page 21


JAVA PROGRAMMING

Examples:
numbers = new int[5]; // Array of size 5
names = new String[3]; // Array of size 3

3. Combined Declaration and Instantiation


You can combine declaration and instantiation in one step.
Syntax:
dataType[] arrayName = new dataType[size];

Examples:
int[] numbers = new int[5];
String[] names = new String[3];

Accessing Array Elements


Access elements using their index. The first element has index 0, the second 1, and so on.

Example:
int[] numbers = {10, 20, 30, 40, 50};
[Link](numbers[0]); // Output: 10
[Link](numbers[3]); // Output: 40

Updating Array Elements


Assign new values to specific indices.
Example:
numbers[2] = 35;
[Link](numbers[2]); // Output: 35

Iterating Through an Array


1. Using a for Loop
for (int i = 0; i < [Link]; i++) {
[Link](arrayName[i]);
}

Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}

2. Using an Enhanced for Loop


for (dataType variable : arrayName) {
// code to execute
}
Example:
for (int num : numbers) {
[Link](num);
}

Types of Arrays in Java


Department of BCA, AIBM Page 22
JAVA PROGRAMMING

In Java, arrays are mainly classified based on their dimensions.

[Link]-Dimensional Array

A one-dimensional array stores a list of elements of the same data type in a single row. It
uses one index to access elements.

Example:

int[] a = {1, 2, 3};

2. Two-Dimensional Array

A two-dimensional array stores data in the form of rows and columns (matrix format). It
uses two indices.

Example:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};

3. Multidimensional Array

A multidimensional array is an array with more than two dimensions. It is mainly used in
complex data storage.

Example:

int[][][] arr = new int[2][3][4];

Objects and classes


Basics of objects and classes in java

Class

 Class is a user defined data type.


 It is a collection of data members and member functions to perform some task.
 A class acts as a template or blueprint for creating objects.
 These properties are stored as data members, and the behaviour is represented by
member functions.
Creation of class:
A class is defined using the keyword class.
Syntax:
<Access specifier> class <class_name>

Department of BCA, AIBM Page 23


JAVA PROGRAMMING

{
<Data members>;
<Member functions>;
}
- Data members are variables which represents properties.
- Member Functions are functions which represents behavior or operations.
Example:
public class C
{
int a,b;
void add( )
{
:::::::::::::
}
}
In the above example,
- public is access specifier.
- class is keyword to define class
- C is name of the class
- a,b are data members.
- add() is member function.

Object.
It is an instance of a class used to access data members and members functions outside of the
class.
Creation of Object
The object can be created by using new keyword.
Syntax:
<class_name> obj_name = new <class_name> (parameters);
Example:
Xyz obj = new Xyz( );
Accessing class members
We can access the data members and member functions outside of the class dot(.) operator.

Department of BCA, AIBM Page 24


JAVA PROGRAMMING

Calling Data Member:


Syntax:
<Obj_name>.var_name;
Example:
obj.a;

Calling Member Function:


Syntax:
<Obj_name>.fn_name(parameters);
Example:
[Link]( );
Difference Between Class and Object

Class Object

Blueprint or template Instance of a class

No memory allocated Memory allocated

Logical entity Physical entity

Example: Student Example: s1, s2

Constructors
They are used to initialize an objects, it has the same name as class and
executes automatically when the objects are created.
Syntax:
Class ClassName
{
ClassName() //Constructor
{
Var_Name = value;
}
}
Example:
class Xyz
{
int a,b;
Xyz( ) //constructor
{
a = 10;
b = 20;
}
}
Xyz obj = new Xyz ( );
[Link]();
Department of BCA, AIBM Page 25
JAVA PROGRAMMING

Rules of constructor
Constructor name should be same as class name
Constructor will not have any return type
Constructor will not return any value
Constructor is always non-static
Whenever an object created constructor will get invoke

Types of Constructors
1. Default constructors (Non- Parameterized Constructors).
2. Parameterized constructors.
3. Constructor Overloading.
Default constructors:
A default constructor does not contain any parameters. If user does not mention default
constructor then Java automatically inserts default constructor and initialize the objects that is
the value zero for integer and float variables, NULL for floating variables and true for Boolean
variables.
Example:
class Xyz
{
int a,b;
Xyz( )
{
a=10;
b=20;
}
void display( )
{
[Link](“a=”+a);
[Link](“b=”+b);
}
}
public static void main ( String [ ] args)
{
Xyz obj = new Xyz ( );
[Link] ( );
Department of BCA, AIBM Page 26
JAVA PROGRAMMING

}
}
Parameterized constructor:
The constructor which contains parameters.
Example:
class Xyz
{
int a,b;
Xyz (int x, int y)
{
a=x;
b=y;
}
void display( )
{
[Link] (“a=”+a);
[Link] (“b=”+b);
}
}
public static void main ( String[ ] args)
{
Xyz obj = new Xyz(100, 200);
[Link] ( );
}
}
Constructor Overloading:
Two or more constructors with different parameters is called Constructor Overloading.
Example:
class Xyz
{
int a, b;
Xyz ( )
{

Department of BCA, AIBM Page 27


JAVA PROGRAMMING

a=0;
b=0;
}
Xyz (int x)
{
a=x;
b=0;
}
Xyz (int x, int y)
{
a=x;
b=y;
}
}
public static void main( String[ ] args)
{
Xyz obj1 = new Xyz ( );
Xyz obj2 = new Xyz (100);
Xyz obj3 = new Xyz (10,20);
}
}
Finalizer in Java

A finalizer in Java is a method that is called by the Garbage Collector (GC) before an object
is destroyed. It is used to perform cleanup operations such as releasing resources (files,
database connections, etc.) before the object is removed from memory.

finalize() Method

Syntax
protected void finalize() throws Throwable
{
// cleanup code
}
Example:
class Test
Department of BCA, AIBM Page 28
JAVA PROGRAMMING

{
protected void finalize()
{
[Link]("Object is destroyed");
}
public static void main(String[] args)
{
Test t = new Test(); // object created
t = null; // object reference removed
[Link](); // request garbage collection
}
}
Output is not guaranteed, because JVM decides when to run Garbage Collector.

Visibility modes/Access Modifier


Visibility modes or modifier are access specfiers or access modifiers. Access
Specifiers is used to restrict the access from one class to another class is called as
access specifiers.
There are four types of Java access modifiers.
1. Private
2. Default
3. Protected
4. Public
Private
Any member which is declared with the keyword then it is called as private.
 It can be access within the class
Example:
private int x;
private void fun()
{
::::::::
}
Default

Department of BCA, AIBM Page 29


JAVA PROGRAMMING

Any member which is not declared any keyword then it is called as default. The
access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If you do not specify any access level, it will be the default.
Example:
class Test // default class
{
int a = 5; // default variable
void show() // default method
{
[Link]("Value = " + a);
}
}
Protected
Any member which is declared with the keyword protected is called as protected
access specifier.
 It can be access within the class
 It can be access with in the package
 It can be access outside the package and within the package with is a relationship
Example:
protected int x;
protected void fun ()
{
:::::::
}
Public
Any member which is declared with the keyword public is called as public access
specifier.
 It can be access within the class
 It can be access within the package
 It can be access anywhere Example:
public int x;
public void fun()
{

Department of BCA, AIBM Page 30


JAVA PROGRAMMING

::::::
}

Outside
Modifier Inside class Inside package package

public ✔️ ✔️ ✔️

protected ✔️ ✔️ ✔️

(default) ✔️ ✔️ ❌

private ✔️ ❌ ❌

Methods and Object


Object in Java
An object is a real world entity.
It represents data (variables) and behavior (methods) together.
Examples of objects:
 Student
 Car
 Mobile
 Book
In Java, an object is created from a class.
Example:
Student s1 = new Student();
Here, s1 is an object of the class Student.

Method in Java
A method is a set of instructions that can be called for execution using the method
name.
▪ A method can take parameters and return a value.
▪ Both parameters and return values are optional.
Department of BCA, AIBM Page 31
JAVA PROGRAMMING

▪ Methods can be public, private or protected.


Why methods are used?
 To reuse code
 To make the program easy to understand
 To avoid repeating code
General form of a method:
returnType methodName()
{
// code
}
Simple Program Using Object and Method
Example:
import [Link].*;
public class Xyz
{
public void display() // method creation
{
[Link]("this is display method");
}
public static void main(String args[])
{
Xyz obj=new Xyz(); // creating an object
[Link](); // access method using object
}
}
Inbuilt Classes in Java
Java provides many inbuilt (predefined) classes in its library to make programming
easy.
[Link] Class
The String class is a built-in class in Java that is used to store and manipulate
sequences of characters.
 Used to store text
 Strings are immutable (cannot be changed)

Department of BCA, AIBM Page 32


JAVA PROGRAMMING

Method Simple Syntax Purpose Example


Finds
number
length() [Link]() "Java".length() → 4
of
characters

Converts
"java".toUpperCase() →
toUpperCase() [Link]() to
JAVA
uppercase

Converts
"JAVA".toLowerCase()
toLowerCase() [Link]() to
→ java
lowercase

Returns
charAt() [Link](index) character "Hello".charAt(1) → e
at index

Compares
"Java".equals("Java") →
equals() [Link](s2) two
true
strings

Joins two "Hello".concat("World")


concat() [Link](s2)
strings → HelloWorld

Extracts
"Program".substring(3)
substring() [Link](start) part of
→ gram
string

Checks
value "Java".contains("Ja") →
contains() [Link](text)
exists or true
not

Removes
trim() [Link]() " Hi ".trim() → Hi
spaces

Replaces "Java".replace('a','o') →
replace() [Link](a,b)
characters Jovo

2. Character Class

Department of BCA, AIBM Page 33


JAVA PROGRAMMING

The Character class provides a set of utility methods for working with
characters. It wraps a char value in an object and offers methods to analyze and
manipulate character data.
 Used to work with single characters
 Part of [Link] package
 Provides utility methods for character checks (e.g., checking if a character is
a letter, digit, whitespace, etc.).

Character Class Methods


Method Simple Syntax Purpose Example
[Link]( Checks isLetter('A')
isLetter()
ch) letter or not →true

[Link]( Checks isDigit('5')


isDigit()
ch) digit or not →true

[Link] Checks isUpperCase('A'


isUpperCase()
Case(ch) uppercase ) → true

[Link] Checks isLowerCase('a')


isLowerCase()
Case(ch) lowercase → true

[Link] Converts to toUpperCase('a')


toUpperCase()
Case(ch) uppercase →A

[Link] Converts to toLowerCase('A'


toLowerCase()
Case(ch) lowercase )→a

[Link] Checks isWhitespace(' ')


isWhitespace()
space(ch) space → true

[Link] Letter or isLetterOrDigit('


isLetterOrDigit()
OrDigit(ch) digit check 9') → true

String buffer class


Java stringBuffer is used to create mutable (modifiable) string object. The
stingBuffer class in java is the same as string class except it is mutable i.e. it can be
changed. StringBuffer is faster than the String class and provides various additional
methods for deleting the sequence elements, updating the sequence elements, etc

Department of BCA, AIBM Page 34


JAVA PROGRAMMING

Method Syntax Description Simple Example


StringBuffer sb=new
Adds text at
StringBuffer("Hi");
append() [Link](str) the end of the
[Link]("
string
All");Output: Hi All

Inserts text at [Link](2,"


[Link](index,
insert() given Java");Output: Hi Java
str)
position All

Replaces
[Link](start,en characters [Link](0,2,"Hello");
replace()
d,str) between Output: Hello Java All
indexes

Deletes
[Link](start,end characters [Link](5,10);Output:
delete()
) between Hello All
indexes

Reverses the [Link]();Output: llA


reverse() [Link]()
string olleH

Returns
capacity() [Link]() current buffer [Link]();Output: 16
capacity

Returns
length() [Link]() length of [Link]();Output: 9
string

Returns
charAt() [Link](index) character at [Link](1);Output: e
index

Changes
setCharA [Link](inde
character at [Link](0,'H');
t() x,ch)
index

Returns
substring [Link](6);Output:
[Link](start) substring
() All
from index

Department of BCA, AIBM Page 35


JAVA PROGRAMMING

File in Java
In Java, a file is used to store data permanently (on hard disk).
Java provides the File class (from [Link] package) to create, read, write, delete,
and get information about files and folders.
Working with Files in Java
File Class ([Link]) The File class represents the pathnames of files and
directories. It provides methods to create, delete, and retrieve file or directory
information.
Common Methods in the File Class
1. createNewFile()
Creates a new file if it does not already exist.
2. delete()
Deletes the file or directory.
3. exists()
Checks if the file or directory exists.
4. getName()
Returns the name of the file.
5. getAbsolutePath()
Returns the absolute pathname string.
6. length()
Returns the length of the file in bytes.
7. isDirectory()
Checks if the file is a directory.
8. isFile()
Checks if the file is a normal file.
9. mkdir()
Creates a directory.
10. list()
Returns an array of names of files and directories in the directory.
This reference/this keyword
"This keyword refers to the current object”. It always points object that is currently
executing. Using this for Ambiguity Variable Names.

Department of BCA, AIBM Page 36


JAVA PROGRAMMING

 this keyword is used whenever the local and global variable names are same to
differentiate between them by use this keyword
 this keyword is also called as default reference variable
 this keyword can be used only the non-static context because this keyword itself is a
non-static
Example:
class Student
{
int age;
Student(int age)
{
[Link] = age;
}
}

I/O Streams Java's


I/O streams are used for input and output operations, such as reading and writing data to
files, memory, or other devices.
Types of Streams
1. Based on Data Type:
o Byte Streams: Handles binary data (e.g., images, videos).
 Classes: InputStream, OutputStream.
o Character Streams: Handles textual data.
 Classes: Reader, Writer.
2. Based on Direction:
o Input Streams: Reads data (e.g., FileInputStream, BufferedReader).
o Output Streams: Writes data (e.g., FileOutputStream, BufferedWriter).
Common Classes
1. Byte Stream Classes:
 FileInputStream: Reads bytes from a file.
 oFileOutputStream:Writes bytes to a file.
 oBufferedInputStream/BufferedOutputStream: Buffers data for efficiency.

Department of BCA, AIBM Page 37


JAVA PROGRAMMING

2. Character Stream Classes:


 FileReader/FileWriter: Reads/Writes characters from/to a file.
 BufferedReader/BufferedWriter: Buffers characters for efficient reading/writing.
3. Data Streams:
 DataInputStream/DataOutputStream: Reads/Writes primitive data types.
4. Serialization:
 ObjectInputStream/ObjectOutputStream: Reads/Writes serialization. objects for

Department of BCA, AIBM Page 38

You might also like