Java Unit1 Introduction
Java Unit1 Introduction
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.
1. Write Code
The developer writes the code in the Java programming language using a text file.
2. Compile
The program is compiled using javac, which is part of the Java Development Kit (JDK).
Run
The Java Virtual Machine (JVM) interprets and executes the bytecode on the target device.
Core Components
Features of Java
Simple
Java is easy to learn, with a syntax that is simple, clean, and easy to understand.
Object-Oriented
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:
No explicit pointer
Robust
The English meaning of Robust is strong. Java is robust for the following reasons:
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.
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 supports dynamic compilation and automatic memory management, including garbage
collection.
}}
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.
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.
class Animal
{
void eat()
{
[Link]("Animal eats");
}
}
class Dog extends Animal
{
void bark()
{
[Link]("Dog barks");
Polymorphism
Polymorphism means one method having many forms.
return a + b;
return a + b + c;
class Animal {
void sound() {
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
void start() {
}
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");
void sound()
[Link]("Dog barks");
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");
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.
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).
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.
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.
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:
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);
}
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
1. Arithmetic Operators
Used for mathematical operations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
== Equal to a == b
!= Not equal to a != b
3. Logical Operators
Used to perform logical operations (mostly with boolean values).
Operator Description Example
! Logical !a
NOT
4. Bitwise Operators
Operate on bits and perform bit-level operations.
Operator Description Example
` ` Bitwise OR
~ Bitwise Complement ~a
5. Assignment Operators
Used to assign values to variables.
Operator Description Example
= Assign a=5
6. Unary Operators
Work with a single operand.
Operator Description Example
+ Unary plus +a
- Unary minus -a
! Logical NOT !a
[Link] Operator
8. Special Operators
Used for specific functionalities.
Operator Description Example
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)
{
}
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");
}
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);
Example:
int[]
numbers = {1, 2, 3, 4, 5};
for (int num : numbers)
{
[Link](num);
}
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
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.
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.
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];
Examples:
numbers = new int[5]; // Array of size 5
names = new String[3]; // Array of size 3
Examples:
int[] numbers = new int[5];
String[] names = new String[3];
Example:
int[] numbers = {10, 20, 30, 40, 50};
[Link](numbers[0]); // Output: 10
[Link](numbers[3]); // Output: 40
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
[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:
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:
Class
{
<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.
Class Object
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 ( )
{
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.
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()
{
::::::
}
Outside
Modifier Inside class Inside package package
public ✔️ ✔️ ✔️
protected ✔️ ✔️ ✔️
(default) ✔️ ✔️ ❌
private ✔️ ❌ ❌
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
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
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
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.).
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
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
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.
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;
}
}