0% found this document useful (0 votes)
7 views175 pages

TVU Java OOP Class Notes

The document provides an overview of Object-Oriented Programming (OOP) using Java, highlighting its key features such as being platform-independent, robust, and secure. It explains fundamental concepts like classes, objects, inheritance, polymorphism, and encapsulation, along with Java's data types, variables, and access modifiers. Additionally, it covers the rules for naming identifiers and the importance of reserved words in Java programming.
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)
7 views175 pages

TVU Java OOP Class Notes

The document provides an overview of Object-Oriented Programming (OOP) using Java, highlighting its key features such as being platform-independent, robust, and secure. It explains fundamental concepts like classes, objects, inheritance, polymorphism, and encapsulation, along with Java's data types, variables, and access modifiers. Additionally, it covers the rules for naming identifiers and the importance of reserved words in Java programming.
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

Object-Oriented Programming

with Java
By
Trishna Ugale
Dept of CSE,COEPTech,Pune
Introduction to JAVA
• Java is a high-level, object-oriented
programming language that is widely used for
developing a variety of software applications.
• It was originally developed by James Gosling and
his team at Sun Microsystems in 1995, and it is
now maintained by Oracle Corporation.
• Java is designed to be simple, robust, secure, and
platform-independent, making it one of the most
popular programming languages in the world.
Key Features of Java
• Object-Oriented:
Java is based on the principles of object-oriented
programming (OOP), which includes concepts like:
• Classes: Blueprints for creating objects.
• Objects: Instances of classes.
• Inheritance: Reusing code by inheriting from existing
classes.
• Polymorphism: Performing a single action in different
ways.
• Encapsulation: Hiding implementation details from
users.

• Platform-Independent:
• Java programs are compiled into bytecode by the
javac compiler.
• This bytecode can run on any platform using the Java
Virtual Machine (JVM), making Java "write once, run
anywhere" (WORA).
•Robust and Secure: Java has strong memory
management, exception handling, and automatic
garbage collection to prevent common programming
errors.
•It also includes built-in security features, such as a
secure runtime environment and cryptography
libraries.
• Multi-threaded:Java supports multi-
threading, enabling the simultaneous
execution of multiple threads, which is ideal
for building responsive applications.

• Rich API and Libraries: Java provides a


comprehensive set of libraries (e.g., [Link],
[Link]) to handle data structures, file I/O,
networking, and more.
How Java Works
• Write the Code: A developer writes Java code
in a file with a .java extension.
• Compile the Code:The javac compiler converts
the .java file into a .class file containing
bytecode (an intermediate, platform-
independent representation of the code)
• The Java Virtual Machine (JVM) executes the
bytecode. The JVM is specific to each platform
(Windows, macOS, Linux), but the bytecode
remains the same, ensuring cross-platform
compatibility.
Here’s a simple example of a Java
program:
• public class HelloWorld
{ public static void main(String[] args)
{ [Link]("Hello, World!");
}
}
public class HelloWorld: Declares a class named
HelloWorld.
main(): The starting point of a Java application.
[Link](): Prints "Hello, World!" to the
console.
Classes and Objects
• • Definition:
• - A class is a blueprint for objects.
• - Objects are instances of a class.
• • Syntax:
• class MyClass {
• int x;
• void display() {
• [Link]("Hello World");
• }
• }
• • Object Creation:
• MyClass obj = new MyClass();
• [Link]();
What is a Class?
• A class is a blueprint or template for creating
objects. It defines the attributes (data) and
methods (functions or behaviors) that the
objects of the class will have.
• Think of a class as a recipe that specifies how
to create something.
•A class contains fields (variables) and
methods (functions).
•It provides a structure for objects to share
common behavior.
•No memory is allocated for a class itself,
only for its objects (instances).
• class ClassName
• {
• // Fields (attributes or properties)
• int field1;
• String field2;
• // Methods (behaviors or functions)
• void method1()
• { [Link]("This is a method.");
• }
• }
• public class Car
• {
• // Attributes String brand;
• int speed;
• // Constructor
• public Car(String brand, int speed)
• {
• [Link] = brand;
• [Link] = speed;
• }
• // Method
• void displayInfo() {
• [Link]("Brand: " + brand + ", Speed: " + speed + " km/h"); }
• }
What is an Object?
• An object is an instance of a class.
• When a class is defined, no memory is
allocated until an object of that class is
created. Each object has:
State: The values of its attributes (fields).
Behavior: The actions it can perform using its
methods.
•Objects are created from classes.
•Objects interact with one another to perform
tasks in a program.
•Each object has its own copy of the
attributes defined in the class.
•Syntax to Create an Object:
ClassName objectName = new ClassName();
• public class Main
• {
• public static void main(String[] args)
• {
• // Creating an object of the Car class
• Car myCar = new Car("Toyota", 120);
• // Call to constructor
• [Link](); // Accessing method of the object
• }
• }
Difference Between Class and Object
Important Components of a Class
• Fields (Attributes):Fields store the data or
properties of an object.
• String color;
• int speed;
• Methods:Methods define the behavior or
functionality of an object.
• void startEngine() {
[Link]("Engine started.");}
• Constructors:A special method used to initialize
objects.
• It has the same name as the class and no return
type.
• public Car(String brand, int speed)
• {
• [Link] = brand;
• [Link] = speed;
• }
Access Modifiers:
• Control access to fields and methods.
• Common modifiers:
• public: Accessible from anywhere.
• private: Accessible only within the class.
• protected: Accessible within the same
package or subclasses.
Why Use Classes and Objects?
• Encapsulation: Combine data and methods into a single
unit.
• Reusability: Classes can be reused to create multiple
objects with similar properties and behaviors.
• Modularity: Breaking down code into smaller,
manageable pieces.
• Scalability: Easy to extend and maintain the codebase.
• Real-World Modeling: Classes and objects allow you to
model real-world entities (e.g., a Car, Person,
BankAccount).
Java Identifiers

• An identifier in Java is the name given to


Variables, Classes, Methods, Packages,
Interfaces, etc.
• These are the unique names and every Java
Variables must be identified with unique
names.
• public class Test
• {
• public static void main(String[] args)
• {
• int a = 20;
• }
• }
• In the above Java code, we have 5 identifiers as follows:
• Test: Class Name
• main: Method Name
• String: Predefined Class Name
• args: Variable Name
• a: Variable Name
Rules For Naming Java Identifiers

• There are certain rules for defining a valid Java


identifier.
• These rules must be followed, otherwise, we
get a compile-time error.
• These rules are also valid for other languages
like C, and C++.
• The only allowed characters for identifiers are all
alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign)
and ‘_‘ (underscore).
• For example “coep@” is not a valid Java identifier as it
contains a ‘@’ a special character.
• Identifiers should not start with digits([0-9]). For example
“123coep” is not a valid Java identifier.
• Java identifiers are case-sensitive.
• There is no limit on the length of the identifier but it is
advisable to use an optimum length of 4 – 15 letters only.
• Reserved Words can’t be used as an identifier. For example
“int while = 20;” is an invalid statement as a while is a
reserved word. There are 53 reserved words in Java.
• MyVariable
• MYVARIABLE
• myvariable
• x
• i
• x1
• i1
• _myvariable
• $myvariable
• sum_of_array
• coep123
Examples of Invalid Identifiers:
• My Variable // contains a space
• 123coep // Begins with a digit
• a+c // plus sign is not an
alphanumeric character
• variable-2 // hyphen is not an
alphanumeric character
• sum_&_difference // ampersand is not an
alphanumeric character
Reserved Words in Java
• Any programming language reserves some
words to represent functionalities defined by
that language.
• These words are called reserved words.
• They can be briefly categorized into two parts:
keywords(50) and literals(3).
• Keywords define functionalities and literals
define value. Identifiers are used by symbol
tables in various analyzing phases(like lexical,
syntax, and semantic) of a compiler
architecture.
• In Java, Keywords are the Reserved words in a
programming language that are used for some
internal process or represent some predefined
actions.
• These words are therefore not allowed to use
as variable names or objects.
• class coep
• {
• public static void main(String[] args)
• {
• // Using final and int keyword
• final int x = 10;

• // Using if and else keywords
• if(x>10){
• [Link]("Failed");
• }
• else{
• [Link]("Succesful Demonstration"
• +" of keywords");
• }
• }
• }
• Java contains a list of keywords or reserved words
which are also highlighted with different colors
be it an IDE or editor in order to segregate the
differences between flexible words and reserved
words.
• NOTE: The keywords const and goto are reserved,
even though they are not currently in use.
• Currently, they are no longer supported in Java.
• true, false, and null look like keywords, but in
actuality they are literals. However, they still can’t
be used as identifiers in a program.
Java Data Types

• Java is statically typed and also a strongly


typed language because, in Java, each type of
data (such as integer, character, hexadecimal,
packed decimal, and so forth) is predefined as
part of the programming language and all
constants or variables defined for a given
program must be described with one of the
Java data types.
• Data types in Java are of different sizes and
values that can be stored in the variable that is
made as per convenience and circumstances to
cover up all test cases. Java has two categories in
which data types are segregated
1. Primitive Data Type: such as boolean, char, int,
short, byte, long, float, and double. The Boolean
with uppercase B is a wrapper class for the
primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type:
such as String, Array, etc.
• // Java Program to demonstrate int data-typeimport
[Link].*;
• class test
• {
• public static void main (String[] args)
• {
• // declaring two int variables
• int a = 10;
• int b = 20;
• [Link]( a + b );
• }
• }
Primitive Data Types in Java

• Primitive data are only single values and have


no special capabilities.
• There are 8 primitive data types.
• They are depicted below in tabular format
below as follows:
Non-Primitive (Reference) Data Types

• The Non-Primitive (Reference) Data Types will contain


a memory address of variable values because the
reference types won’t store the variable value directly
in memory. They are strings, objects, arrays, etc.
• 1. Strings
• Strings are defined as an array of characters. The
difference between a character array and a string in
Java is, that the string is designed to hold a sequence of
characters in a single variable whereas, a character
array is a collection of separate char-type entities.
Unlike C/C++, Java strings are not terminated with a
null character.
• // Declare String without using new operator
• String s = “COEPTECH";
• // Declare String using new operator
• String s1 = new String(" COEPTECH ");

• [Link] : An Array is a group of like-typed variables that are referred to by a


common name. Arrays in Java work differently than they do in C/C++.
• In Java, all arrays are dynamically allocated.
• Since arrays are objects in Java, we can find their length using member length. This
is different from C/C++ where we find length using size.
• A Java array variable can also be declared like other variables with [] after the data
type.
• The variables in the array are ordered and each has an index beginning with 0.
• Java array can also be used as a static field, a local variable, or a method
parameter.
• The size of an array must be specified by an int value and not long or short.
Java Variables

• Variables are the containers for storing the


data values or you can also call it a memory
location name for the data. Every variable has
a: Data Type – The kind of data that it can
hold. For example, int, string, float, char, etc.
• Variable Name – To identify the variable
uniquely within the scope.
• Value – The data assigned to the variable.
• There are three types of variables in Java –
Local, Instance, and Static.
• 1. Local Variables
• A variable defined within a block or method or
constructor is called a local variable.
• The Local variable is created at the time of declaration
and destroyed after exiting from the block or when the
call returns from the function.
• The scope of these variables exists only within the
block in which the variables are declared, i.e., we can
access these variables only within that block.
• Initialization of the local variable is mandatory before
using it in the defined scope.
• 2. Instance Variables
• Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.
• As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access specifiers for instance variables. If we do
not specify any access specifier, then the default access specifier will be used.
• Initialization of an instance variable is not mandatory. Its default value is
dependent on the data type of variable. For String it is null, for float it is 0.0f, for
int it is 0, for Wrapper classes like Integer it is null, etc.
• Scope of instance variables are throughout the class except the static contexts.
• Instance variables can be accessed only by creating objects.
• We initialize instance variables using constructors while creating an object. We can
also use instance blocks to initialize the instance variables.
• // Java Program to show the use of
• // Instance Variables
• import [Link].*;

• class demo {

• // Declared Instance Variable


• public String coep;
• public int i;
• public Integer I;
• public demo()
• {
• // Default Constructor
• // initializing Instance Variable
• [Link] = “COEPTech";
• }

• // Main Method
• public static void main(String[] args)
• {
• // Object Creation
• demo name = new demo();

• // Displaying O/P
• [Link](“College name is: " + [Link]);
• [Link]("Default value for int is "+ name.i);

• // toString() called internally
• [Link]("Default value for Integer is "+ name.I);
• }
• }
• College name is: COEPTech
• Default value for int is 0
• Default value for Integer is null
• // Java Program to Illustrate Usage of Instance Blocks

• // Class 1
• // Helper class
• class coep {

• // Constructors of this class

• // Constructor 1
• // This constructor will get executed for 1st
• // kind of object
• coep()
• {
• [Link]("1st argument constructor");
• }

• // Constructor 2
• // This constructor will get executed for
• // 2nd kind of object
• coep(String a)
• {

• // Print statement when this constructor is called


• [Link]("2nd argument constructor");
• }

• // Constructor 3
• // This constructor will get executed
• // for 3rd kind of object
• coep(int a, int b)
• {

• // Print statement when this constructor is called


• [Link]("3rd arguments constructor");
• }

• {
• // Creation of an instance block
• [Link]("Instance block");
• }
• }
• // Class 2
• // Main class
• class coepJava {

• // main driver method


• public static void main(String[] args)
• {

• // Object of 1st kind


• new coep();

• // Object of 2nd kind


• new coep("I like Java");

• // Object of 3rd kind


• new coep(10, 20);
• }
• }
Static Variables

• Static variables are also known as class variables.


• These variables are declared similarly to instance variables. The difference is that static variables
are declared using the static keyword within a class outside of any method, constructor, or block.
• Unlike instance variables, we can only have one copy of a static variable per class, irrespective of
how many objects we create.
• Static variables are created at the start of program execution and destroyed automatically when
execution ends.
• Initialization of a static variable is not mandatory. Its default value is dependent on the data type of
variable. For String it is null, for float it is 0.0f, for int it is 0, for Wrapper classes like Integer it is null,
etc.
• If we access a static variable like an instance variable (through an object), the compiler will show a
warning message, which won’t halt the program. The compiler will replace the object name with
the class name automatically.
• If we access a static variable without the class name, the compiler will automatically append the
class name. But for accessing the static variable of a different class, we must mention the class
name as 2 different classes might have a static variable with the same name.
• Static variables cannot be declared locally inside an instance method.
• // Java Program to show the use of
• // Static variables
• import [Link].*;

• class demo {
• // Declared static variable
• public static String name = "ABCD";

• public static void main(String[] args)
• {

• // name variable can be accessed without object


• // creation Displaying O/P [Link] --> using the
• // static variable
• [Link]("Name is : " + [Link]);

• // static int c = 0;
• // above line, when uncommented,
• // will throw an error as static variables cannot be
• // declared locally.
• }
• }
Instance Variables vs Static Variables

• Each object will have its own copy of an instance variable, whereas
we can only have one copy of a static variable per class, irrespective
of how many objects we create. Thus, static variables are good for
memory management.
• Changes made in an instance variable using one object will not be
reflected in other objects as each object has its own copy of the
instance variable. In the case of a static variable, changes will be
reflected in other objects as static variables are common to all
objects of a class.
• We can access instance variables through object references, and
static variables can be accessed directly using the class name.
• Instance variables are created when an object is created with the
use of the keyword ‘new’ and destroyed when the object is
destroyed. Static variables are created when the program starts and
destroyed when the program stops.
• Static Methods in Java
1.A static method is a method that belongs to the
class rather than any specific instance of the class.
[Link] can be called directly using the class name,
without creating an object of the class.
• Access without an object
• Static methods can be called using the class name directly, e.g.,
[Link]().
• Cannot use non-static members directly
• Static methods cannot directly access non-static variables or call non-static
methods of the class because static methods do not have access to the
this keyword (which refers to an instance of the class).
• Commonly used for utility or helper functions
• Static methods are typically used for operations that don't depend on
instance variables, such as mathematical calculations ([Link]()), utility
functions, or factory methods.
• Can be overloaded
• Static methods can be overloaded (defined with different parameter lists),
but they cannot be overridden in the true sense of polymorphism because
they are not associated with instances.
• class StaticExample
• {
• // Static variable
• static String greeting = "Hello, World!";
• // Static method static void printGreeting()
• {
• [Link](greeting);
• }
• // Non-static method
• void nonStaticMethod()
• {
• [Link]("This is a non-static method.");
• }
• public static void main(String[] args)
• {
• // Calling the static method directly using the class name
• [Link]();
• // Cannot call a non-static method without creating an instance
• // [Link]();
• // This would cause a compilation error
• // Creating an instance to call the non-static method
• StaticExample obj = new StaticExample();
• [Link]();
• }
• }
Java Operators

• Java operators are special symbols that perform


operations on variables or values. They can be
classified into several categories based on their
functionality.
• These operators play a crucial role in performing
– Arithmetic
– Logical
– Relational
– bitwise operations etc.
Types of Operators in Java

1. Arithmetic Operators:+,-,*/,%
2. Unary Operators:-,+,++,--,!
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
[Link] Operators
• Unary Operators need only one operand. They are used to
increment, decrement, or negate a value.
• - , Negates the value.
• + , Indicates a positive value (automatically converts byte,
char, or short to int).
• ++ , Increments by 1.
• Post-Increment: Uses value first, then increments.
• Pre-Increment: Increments first, then uses value.
• -- , Decrements by 1.
• Post-Decrement: Uses value first, then decrements.
• Pre-Decrement: Decrements first, then uses value.
• ! , Inverts a boolean value.
• // Java Program to show the use of
• // Unary Operators
• import [Link].*;
• // Driver Class
• class Demo {
• // main function
• public static void main(String[] args)
• {
• // Interger declared
• int a = 10; int b = 10;
• // Using unary operators
• [Link]("Postincrement : " + (a++));
• [Link]("Preincrement : " + (++a));
• [Link]("Postdecrement : " + (b--));
• [Link]("Predecrement : " + (--b));
• }
• }
3. Assignment Operator

• ‘=’ Assignment operator is used to assign a value


to any variable. It has right-to-left associativity,
i.e. value given on the right-hand side of the
operator is assigned to the variable on the left,
and therefore right-hand side value must be
declared before using it or should be a constant.

• The general format of the assignment operator is:

• variable = value;
• In many cases, the assignment operator can be
combined with others to create shorthand compound
statements.
• For example, a += 5 replaces a = a + 5. Common
compound operators include:

• += , Add and assign.


• -= , Subtract and assign.
• *= , Multiply and assign.
• /= , Divide and assign.
• %= , Modulo and assign.
4. Relational Operators

• Relational Operators are used to check for relations like equality,


greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well
as conditional if-else statements. The general format is ,
• variable relation_operator value
• Relational operators compare values and return boolean results:

• == , Equal to.
• != , Not equal to.
• < , Less than.
• <= , Less than or equal to.
• > , Greater than.
• >= , Greater than or equal to.
5. Logical Operators

• Logical Operators are used to perform “logical AND” and “logical


OR” operations, similar to AND gate and OR gate in digital
electronics. They have a short-circuiting effect, meaning the second
condition is not evaluated if the first is false.

• Conditional operators are:

• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-
versa
6. Ternary operator

• The Ternary Operator is a shorthand version of


the if-else statement. It has three operands and
hence the name Ternary. The general format is ,

• condition ? if true : if false

• The above statement means that if the condition


evaluates to true, then execute the statements
after the ‘?’ else execute the statements after the
‘:’.
• // Java program to illustrate
• // max of three numbers using
• // ternary operator.

• public class Demo {



• public static void main(String[] args)
• {
• int a = 20, b = 10, c = 30, result;

• // result holds max of three


• // numbers
• result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
• [Link]("Max of three numbers = "+ result);
• }
• }
7. Bitwise Operators

• Bitwise Operators are used to perform the manipulation of


individual bits of a number and with any of the integer
types. They are used when performing update and query
operations of the Binary indexed trees.

• & (Bitwise AND) – returns bit-by-bit AND of input values.


• | (Bitwise OR) – returns bit-by-bit OR of input values.
• ^ (Bitwise XOR) – returns bit-by-bit XOR of input values.
• ~ (Bitwise Complement) – inverts all bits (one’s
complement).
8. Shift Operators

• Shift Operators are used to shift the bits of a number left or right,
thereby multiplying or dividing the number by two, respectively.
They can be used when we have to multiply or divide a number by
two. The general format ,

• number shift_op number_of_places_to_shift;

• << (Left shift) – Shifts bits left, filling 0s (multiplies by a power of


two).
• >> (Signed right shift) – Shifts bits right, filling 0s (divides by a
power of two), with the leftmost bit depending on the sign.
• >>> (Unsigned right shift) – Shifts bits right, filling 0s, with the
leftmost bit always 0.
• // Java Program to show the use of
• // shift operators
• import [Link].*;
• class Demo
• {
• public static void main(String[] args)
• {
• int a = 10;
• // Using left shift
• [Link]("a<<1 : " + (a << 1));
• // Using right shift
• [Link]("a>>1 : " + (a >> 1));
• }
• }
• Expression: a << 1
• The binary representation of 10 is: 0000 1010 (8 bits for simplicity).

• When you apply a left shift by 1 bit (a << 1), the bits are shifted to the left, and a 0 is added at the right end:
• 0000 1010 -> 0001 0100
• New value: The binary 0001 0100 corresponds to the decimal value 20.
• 1. Binary: 00000101

• This binary number has eight bits. Starting from the rightmost bit:
• Bit Position (Right to Left) 7 6 5 4 3 2 1 0
• Binary Value 0 0 0 0 0 1 0 1

• Each position represents a power of 2, starting with 20=120=1 at position 0. Let’s calculate:

• 2^0=1 (rightmost bit, and it's 1)


• 2^1=2 (second bit from the right, and it's 0)
• 2^2=4 (third bit from the right, and it's 1)

• Now sum the values for bits that are 1:


• 4+1=5

• So, 00000101 in binary is 5 in decimal.


• 2. Binary: 00010100

• Now let’s look at this number:


• Bit Position (Right to Left) 7 6 5 4 3 2 1 0
• Binary Value 0 0 0 1 0 1 0 0

• Each position again represents a power of 2:

• 2^0=1 (rightmost bit, and it's 0)


• 2^1=2 (second bit from the right, and it's 0)
• 2^2=4 (third bit from the right, and it's 1)
• 2^4=16 (fifth bit from the right, and it's 1)

• Now sum the values for bits that are 1:


• 16+4=20

• So, 00010100 in binary is 20 in decimal.


• Right Shift (>>) Operator:

• Expression: a >> 1

• Explanation: The right shift operator shifts the bits of the number to the right by the specified
number of positions. In this case, a >> 1 means shifting the bits of a one position to the right.

• Effect on Bits:

• The binary representation of 10 is: 0000 1010 (8 bits for simplicity).

• When you apply a right shift by 1 bit (a >> 1), the bits are shifted to the right, and the leftmost
bit (most significant bit) is filled with the sign bit (0 for positive numbers).

• 0000 1010 -> 0000 0101

• New value: The binary 0000 0101 corresponds to the decimal value 5.

• Result: a >> 1 prints 5.


• Summary of the Outputs:
• a << 1: The value of a is left-shifted by one
position. This multiplies the value by 2. Since a
= 10, the result is 20.
• a >> 1: The value of a is right-shifted by one
position. This divides the value by 2 (integer
division). Since a = 10, the result is 5.
Precedence of Arithmatic operators
• The precedence of arithmetic operators in Java
determines the order in which expressions are
evaluated when multiple operators are used
without parentheses.
• The precedence of arithmetic operators in Java
(from highest to lowest):
• Multiplication (*), Division (/), and Modulus (%)
• These operators have the highest precedence
among arithmetic operators and are evaluated
from left to right.
• Addition (+) and Subtraction (-)
• These have lower precedence compared to multiplication, division, and
modulus, but are also evaluated from left to right.
• public class OperatorPrecedence {
• public static void main(String[] args) {
• int result = 10 + 2 * 5 - 3 / 3;
• // Steps of evaluation:
• // 1. Multiplication: 2 * 5 = 10
• // 2. Division: 3 / 3 = 1
• // 3. Addition: 10 + 10 = 20
• // 4. Subtraction: 20 - 1 = 19
• [Link]("Result: " + result); // Output: 19
• }
• }
• Operators with higher precedence are evaluated first.
• Operators with the same precedence are evaluated left to right
(associativity).
• Use parentheses to explicitly define the order of evaluation if the
default precedence is not desirable.
• 9-12/(3+3)*(2-1)
• Expressions within parentheses assume highest [Link] two or
more sets of parentheses appear one after another ,[Link]
in left most set is evaluated first and then right most in last.
• 1st pass:9-12/6*(2-1)
• pass:9-12/6*1
• 2nd pass:9-2*1
• pass:9-2
• 3rd pass: 7
Typecasting
• Typecasting in Java is the process of converting
one data type to another data type using the
casting operator.
• When you assign a value from one primitive data
type to another type, this is known as type
casting.
• To enable the use of a variable in a specific
manner, this method requires explicitly
instructing the Java compiler to treat a variable of
one data type as a variable of another data type.
Syntax:
• <datatype> variableName = (<datatype>)
value;
• Types of Type Casting
• Widening Type Casting
• Narrow Type Casting
Widening Type Casting
• A lower data type is transformed into a higher
one by a process known as widening type casting.
Implicit type casting and casting down are some
names for it.
• Since there is no chance of data loss, it is secure.
Widening Type casting occurs when:
• The target type must be larger than the source
type.
• Both data types must be compatible with each
other.
• Syntax: larger_data_type variable_name = smaller_data_type_variable;

• // Java program to demonstrate Widening TypeCasting


• import [Link].*;

• class Test {
• public static void main(String[] args)
• {
• int i = 10;

• // Wideing TypeCasting (Automatic Casting)


• // from int to long
• long l = i;

• // Wideing TypeCasting (Automatic Casting)


• // from int to double
• double d = i;

• [Link]("Integer: " + i);


• [Link]("Long: " + l);
• [Link]("Double: " + d);
• }
• }

• Output:
• Integer: 10
• Long: 10
• Double: 10.0
Narrow Type Casting
• The process of downsizing a bigger data type into
a smaller one is known as narrowing type casting.
• Casting up or explicit type casting are other
names for it. It doesn’t just happen by itself. If we
dont explicitly do that, a compile-time error will
occur.
• Narrowing type casting is unsafe because data
loss might happen due to the lower data type’s
smaller range of permitted values. A cast
operator assists in the process of explicit casting.
• Syntax:
• smaller_data_type variable_name = (smaller_data_type) larger_data_type_variable;
• // Java Program to demonstrate Narrow type casting
• import [Link].*;

• class Test {
• public static void main(String[] args)
• {
• double i = 100.245;

• // Narrowing Type Casting


• short j = (short)i; …//explicit typecast
• int k = (int)i;

• [Link]("Original Value before Casting"


• + i);
• [Link]("After Type Casting to short "
• + j);
• [Link]("After Type Casting to int "
• + k);
• }
• }

• Output:

• Original Value before Casting 100.245


• After Type Casting to short 100
• After Type Casting to int 100
Casts that results in No Loss of information
FROM TO
Byte Short,char,int,long,float,double
short Int,long,float,double
char Int,long,float,double
int Long,float,double
Long Float,double
Float double
Constant
• Constant is a value that cannot be changed after
assigning it. Java does not directly support the
constants.
• There is an alternative way to define the
constants in Java by using the non-access
modifiers static and final.
• In Java, to declare any variable as constant, we
use static and final modifiers. It is also known as
non-access modifiers. According to the Java
naming convention the identifier name must be
in capital letters.
Static and Final Modifiers
• The purpose to use the static modifier is to
manage the memory.
• It also allows the variable to be available without
loading any instance of the class in which it is
defined.
• The final modifier represents that the value of
the variable cannot be changed. It also makes the
primitive data type immutable or unchangeable.
• Syntax:
static final datatype identifier_name=value;
Control Statements
• In Java, control statements manage the flow
of execution of the program based on
conditions, loops, or branching.
• They determine the order in which
instructions are executed, which makes Java
programs dynamic and responsive.
• Java control statements are broadly classified
into three types:
• 1. Decision-Making Statements
• 2. Looping Statements
• 3. Jump Statements
1. Decision-Making Statements

• The Java if statement is the most simple decision-making


statement.
• It is used to decide whether a certain statement or block of
statements will be executed or not i.e. if a certain condition
is true then a block of statements is executed otherwise
not.
• Syntax:
• if(condition)
• {
• // Statements to execute if
• // condition is true
• }
• Working of if statement:
1. Control falls into the if block.
2. The flow jumps to Condition.
3. Condition is tested.
1. If Condition yields true, goto Step 4.
[Link] Condition yields false, goto Step 5.
4. The if-block or the body inside the if is executed.
5. Flow steps out of the if block.
• // Java program to illustrate If statement
• class Test{
• public static void main(String args[])
• {
• String str = “COEPTech";
• int i = 4;

• // if block
• if (i == 4) {
• i++;
• [Link](str);
• }

• // Executed by default
• [Link]("i = " + i);
• }
• }
Java if-else Statement
• The if-else statement in Java is a powerful
decision-making tool used to control the
program’s flow based on conditions.
• It executes one block of code if a condition is
true and another block if the condition is
false.
Syntax of if-else Statement
• if (condition)
• {
• // Executes this block if
• // condition is true
• }
• else
• {
• // Executes this block if
• // condition is false
• }
• // Java Program to demonstrate
• // if-else statement
• public class IfElse {

• public static void main(String[] args) {

• int n = 20;

• if (n > 5) {
• [Link]("The number is greater than 5.");
• } else {
• [Link]("The number is 5 or less.");
• }
• }
• }
Java if-else-if ladder with Examples
• The Java if-else-if ladder is used to evaluate
multiple conditions sequentially.
• It allows a program to check several conditions
and execute the block of code associated with the
first true condition.
• If none of the conditions are true, an optional
else block can execute as a fallback.
• Example: The below example demonstrates a
straightforward if-else-if ladder structure. It
evaluates a number and prints the corresponding
message based on the condition.
Syntax of if-else-if ladder:
• if (condition)
• statement 1;
• else if (condition)
• statement 2;
• .
• .
• else
• statement;
• // Java program to illustrate if-else-if ladder
• import [Link].*;

• class Test {

• public static void main(String[] args) {

• // initializing expression
• int i = 20;

• // condition 1
• if (i == 10)
• [Link]("i is 10\n");

• // condition 2
• else if (i == 15)
• [Link]("i is 15\n");

• // condition 3
• else if (i == 20)
• [Link]("i is 20\n");

• else
• [Link]("i is not present\n");

• [Link]("Outside if-else-if");
• }
• }
Switch Statements in Java
• The switch statement in Java is a multi-way
branch statement. In simple words, the Java
switch statement executes one statement
from multiple conditions.
• It is an alternative to an if-else-if ladder
statement. It provides an easy way to dispatch
execution to different parts of code based on
the value of the expression.
Syntax:
• switch(expression)
• {
• case value1 :
• // Statements
• break; // break is optional

• case value2 :
• // Statements
• break; // break is optional
• ....
• ....
• ....
• default :
• // default Statement
• }
Default statement in Java Switch Case
• The default case in a switch statement specifies
the code to run if no other case matches. It can
be placed at any position in the switch block but
is commonly placed at the end.
• Note: Regardless of its placement, the default
case only gets executed if none of the other case
conditions are met. So, putting it at the
beginning, middle, or end doesn’t change the
core logic
• Case label variations
• Case labels and switch arguments can be
constant expressions.
• The switch argument can be a variable
expression but the case labels must be
constant expressions.
• import [Link].*;

• class Testswitch {
• public static void main(String[] args)
• {
• int x = 2;
• switch (x + 1) {
• case 1:
• [Link](1);
• break;
• case 1 + 1:
• [Link](2);
• break;
• case 2 + 1:
• [Link](3);
• break;
• default:
• [Link]("Default");
• }
• }
• }
Case Label Cannot Be Variable
• A case label cannot be a variable or variable expression. It must be a constant expression.
• import [Link].*;
• class Testsw
• {
• public static void main(String[] args)
• {
• int x = 2;
• int y = 1;
• switch (x)
• {
• case 1: [Link](1);
• break;
• case 2: [Link](2);
• break;
• case x + y: [Link](3);
• break;
• default:
• [Link]("Default");
• }
• }
• }
Jump Statements
• Java supports three jump statements:
• break,
• Continue
• return
• These three statements transfer control to another part of the program.

• Break: In Java, a break is majorly used for:


• Terminate a sequence in a switch statement (discussed above).
• To exit a loop.
• Used as a “civilized” form of goto.
• Continue: Sometimes it is useful to force an early iteration of a loop.
• That is, you might want to continue running the loop but stop processing
the remainder of the code in its body for this particular iteration.
• This is, in effect, a goto just past the body of the loop, to the loop’s end.
The continue statement performs such an action.
• // Java program to demonstrates the use of
• // continue in an if statement
• import [Link].*;

• class Test {
• public static void main(String args[])
• {
• for (int i = 0; i < 10; i++) {

• // If the number is even
• // skip and continue
• if (i % 2 == 0)
• continue;

• // If number is odd, print it


• [Link](i + " ");
• }
• }
• }
• Return Statement
• The return statement is used to explicitly return from a method.
• It causes program control to transfer back to the caller of the method.

• // Java program to demonstrate the use of return


• import [Link].*;

• class Test {
• public static void main(String args[])
• {
• boolean t = true;
• [Link] ("Before the return.");

• if (t)
• return;

• // Compiler will bypass every statement


• // after return
• [Link] ("This won't execute.");
• }
• }
• Output: Before the return
Java Loops
• Looping in programming languages is a feature that
facilitates the execution of a set of
instructions/functions repeatedly while some condition
evaluates to true.
• Java provides three ways for executing the loops. While
all the ways provide similar basic functionality, they
differ in their syntax and condition-checking time.
• In Java, there are three types of Loops which are
listed below:
• for loop
• while loop
• do-while loop
Java For Loop
• Java for loop is a control flow statement that allows code to be
executed repeatedly based on a given condition.
• The for loop is used when we know the number of iterations (we
know how many times we want to repeat a task).
• The for statement consumes the initialization, condition, and
increment/decrement in one line thereby providing a shorter, easy-
to-debug structure of looping.
• Syntax
• for (initialization expr; condition; increment/decrement)
{
// body of the loop
// statements we want to execute
}
• Initialization condition: Here, we initialize the variable in use. It
marks the start of a for loop. An already declared variable can be
used or a variable can be declared, local to loop only.
• Testing Condition: It is used for testing the exit condition for a loop.
It must return a boolean value. It is also an Entry Control Loop as
the condition is checked prior to the execution of the loop
statements.
• Statement execution: Once the condition is evaluated to true, the
statements in the loop body are executed.
• Increment/ Decrement: It is used for updating the variable for next
iteration.
• Loop termination: When the condition becomes false, the loop
terminates marking the end of its life cycle.
• // Java program to print numbers from 1 to 10
• class Test
• {
• public static void main(String[] args)
• {
• for (int i = 1; i <= 10; i++)
{
• [Link](i);
• }
• }
• }
• // Java program to illustrate for loop
• class Test
• {
• public static void main(String args[])
• {
• // Writing a for loop
• // to print Hello World 5 times
• for (int i = 1; i <= 5; i++)
[Link]("Hello World");
• }
• }
• Enchanced for loop (for each)

• This loop is used to iterate over arrays or collections.

• Syntax:

• for (dataType variable : arrayOrCollection) {

• // code to be executed

• }
• // Java program to demonstrates the working of for each loop
• import [Link].*;

• class Testfor {
• public static void main(String[] args)
• {
• int[] arr = { 1, 2, 3, 4, 5 };

• for (int i : arr) {


• [Link](i + " ");
• }
• }
• }
2. while Loop

• A while loop is used when we want to check the


condition before running the code.

• Syntax:

• while (condition) {

• // code to be executed

• }
• While loop starts with the checking of Boolean
condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement
following the loop is executed. For this reason it is also
called Entry control loop
• Once the condition is evaluated to true, the statements
in the loop body are executed. Normally the
statements contain an update value for the variable
being processed for the next iteration.
• When the condition becomes false, the loop
terminates which marks the end of its life cycle.
• // Java program to demonstrates
• // the working of while loop
• import [Link].*;

• Class Testwhile {
• public static void main(String[] args)
• {
• int i = 0;
• while (i <= 10) {
• [Link](i + " ");
• i++;
• }
• }
• }
• o/p:0 1 2 3 4 5 6 7 8 9 10
3. do-while Loop

• The do-while loop in Java ensures that the code


block executes at least once before the condition
is checked.
• Syntax:

• do {

• // code to be executed

• } while (condition);
• do while loop starts with the execution of the statement(s).
There is no checking of any condition for the first time.
• After the execution of the statements, and update of the
variable value, the condition is checked for true or false
value. If it is evaluated to true, next iteration of loop starts.
• When the condition becomes false, the loop terminates
which marks the end of its life cycle.
• It is important to note that the do-while loop will execute
its statements atleast once before any condition is checked,
and therefore is an example of exit control loop.
• // Java program to demonstrates
• // the working of do-while loop
• import [Link].*;

• class Testdo {
• public static void main(String[] args)
• {
• int i = 0;
• do {
• [Link](i + " ");
• i++;
• } while (i <= 10);
• }
• }
• Pitfalls of Loops
• If loops are not used correctly, they can
introduce pitfalls and bugs that affect code
performance, readability, and functionality.
Below are some common pitfalls of loops:
Arrays in Java

• Arrays are fundamental structures in Java that allow us


to store multiple values of the same type in a single
variable. They are useful for storing and managing
collections of data.
• Arrays in Java are objects, which makes them work
differently from arrays in C/C++ in terms of memory
management.
• For primitive arrays, elements are stored in a
contiguous memory location.
• For non-primitive arrays, references are stored at
contiguous locations, but the actual objects may be at
different locations in memory.
• public class Main {
• public static void main(String[] args)
• {

• // initializing array
• int[] arr = { 1, 2, 3, 4, 5 };

• // size of array
• int n = [Link];

• // traversing array
• for (int i = 0; i < n; i++)
• [Link](arr[i] + " ");
• }
• }
Basics of Arrays in Java

• 1. Array Declaration
• To declare an array in Java, use the following
syntax:
type[] arrayName;
type: The data type of the array elements
(e.g., int, String).
arrayName: The name of the array.
2. Create an Array

• To create an array, you need to allocate memory


for it using the new keyword:

• // Creating an array of 5 integers


• numbers = new int[5];

• This statement initializes the numbers array to


hold 5 integers. The default value for each
element is 0.
3. Access an Element of an Array

• We can access array elements using their index, which


starts from 0:

• // Setting the first element of the array


• numbers[0] = 10;

• // Accessing the first element


• int firstElement = numbers[0];

• The first line sets the value of the first element to 10.
The second line retrieves the value of the first element.
4. Change an Array Element
• To change an element, assign a new value to a
specific index:

• // Changing the first element to 20


• numbers[0] = 20;
5. Array Length

• We can get the length of an array using the length


property:

• // Getting the length of the array


• int length = [Link];

• Now, we have completed with basic operations so


let us go through the in-depth concepts of Java
Arrays, through the diagrams, examples, and
explanations.
Array Properties

• In Java, all arrays are dynamically allocated.


• Arrays may be stored in contiguous memory [consecutive
memory locations].
• Since arrays are objects in Java, we can find their length
using the object property length. This is different from
C/C++, where we find length using size of.
• A Java array variable can also be declared like other
variables with [] after the data type.
• The variables in the array are ordered, and each has an
index beginning with 0.
• Java array can also be used as a static field, a local
variable, or a method parameter.
• An array can contain primitives (int, char, etc.)
and object (or non-primitive) references of a
class, depending on the definition of the array.
• In the case of primitive data types, the actual
values might be stored in contiguous memory
locations (JVM does not guarantee this
behavior).
• In the case of class objects, the actual objects
are stored in a heap segment.
Creating, Initializing, and Accessing an
Arrays in Java
• For understanding the array we need to
understand how it actually works. To
understand this follow the flow mentioned
below:
• Declare
• Initialize
• Access
i. Declaring an Array

• The general form of array declaration is

• Method 1:
• type var-name[];

• Method 2:
• type[] var-name;

• The element type determines the data type of each element that
comprises the array. Like an array of integers, we can also create an
array of other primitive data types like char, float, double, etc., or
user-defined data types (objects of a class).
ii. Initialization an Array in Java

• When an array is declared, only a reference of an array


is created. The general form of new as it applies to
one-dimensional arrays appears as follows:

• var-name = new type [size];

• Here, type specifies the type of data being allocated,


size determines the number of elements in the array,
and var-name is the name of the array variable that is
linked to the array. To use new to allocate an array, you
must specify the type and number of elements to
allocate.
• Example:

• // declaring array
• int intArray[];

• // allocating memory to array


• intArray = new int[20];

• // combining both statements in one


• int[] intArray = new int[20];

• Note: The elements in the array allocated by new will automatically be


initialized to zero (for numeric types), false (for boolean), or null (for
reference types).
• Obtaining an array is a two-step process.
• First, you must declare a variable of the
desired array type.
• Second, you must allocate the memory to
hold the array, using new, and assign it to the
array variable. Thus, in Java, all arrays are
dynamically allocated.
iii. Accessing Java Array Elements using
for Loop
• Now , we have created an Array with or without the values stored
in it. Access becomes an important part to operate over the values
mentioned within the array indexes using the points mentioned
below:

• Each element in the array is accessed via its index.


• The index begins with 0 and ends at (total array size)-1.
• All the elements of array can be accessed using Java for Loop.

• Let us check the syntax of basic for loop to traverse an array:

• // Accessing the elements of the specified array


• for (int i = 0; i < [Link]; i++)
• [Link](“Element at index ” + i + ” : “+ arr[i]);
• class Test{
• public static void main(String[] args)
• {
• // declares an Array of integers.
• int[] arr;

• // allocating memory for 5 integers.


• arr = new int[5];

• // initialize the elements of the array


• // first to last(fifth) element
• arr[0] = 10;
• arr[1] = 20;
• arr[2] = 30;
• arr[3] = 40;
• arr[4] = 50;

• // accessing the elements of the specified array


• for (int i = 0; i < [Link]; i++)
• [Link]("Element at index "
• + i + " : " + arr[i]);
• }
• }
• Element at index 0 : 10
• Element at index 1 : 20
• Element at index 2 : 30
• Element at index 3 : 40
• Element at index 4 : 50
Types of Arrays in Java

• 1. Single-Dimensional Arrays
• // A single-dimensional array
int[] singleDimArray = {1, 2, 3, 4, 5};
• 2. Multi-Dimensional Arrays
• Arrays with more than one dimension, such as
two-dimensional arrays (matrices).

• // A 2D array (matrix)
• int[][] multiDimArray = {
• {1, 2, 3},
• {4, 5, 6},
• {7, 8, 9} };
Arrays of Objects in Java

• An array of objects is created like an array of


primitive-type data items in the following way.
• Syntax:

• Method 1:
• ObjectType[] arrName;

• Method 2:
• ObjectType arrName[];
Example of Arrays of Objects

• Example 1: Here we are taking a student class


and creating an array of Student with five
Student objects stored in the array. The
Student objects have to be instantiated using
the constructor of the Student class, and their
references should be assigned to the array
elements.
• // Java program to illustrate creating an array
• // of integers, puts some values in the array,
• // and prints each value to standard output.

• // Java program to illustrate creating


• // an array of objects

• class Student {
• public int roll_no;
• public String name;

• Student(int roll_no, String name){
• this.roll_no = roll_no;
• [Link] = name;
• }
• }
• public class Main {
• public static void main(String[] args){

• // declares an Array of Student
• Student[] arr;

• // allocating memory for 5 objects of type Student.


• arr = new Student[5];

• // initialize the elements of the array


• arr[0] = new Student(1, "aman");
• arr[1] = new Student(2, "vaibhav");
• arr[2] = new Student(3, "shikar");
• arr[3] = new Student(4, "dharmesh");
• arr[4] = new Student(5, "mohit");

• // accessing the elements of the specified array


• for (int i = 0; i < [Link]; i++)
• [Link]("Element at " + i + " : { "
• + arr[i].roll_no + " "
• + arr[i].name+" }");
• }
• }
"Understanding Strings in Java"
• Strings are used for storing text.
• A String variable contains a collection of characters
surrounded by double quotes:
• String greeting = "Hello";
• A String in Java is actually an object, which contain
methods that can perform certain operations on
strings. For example, the length of a string can be
found with the length() method:
• String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
• [Link]("The length of the txt string is: " +
[Link]());
• There are many string methods available, for
example toUpperCase() and toLowerCase():
• String txt = "Hello World";
• [Link]([Link]()); //
Outputs "HELLO WORLD"
• [Link]([Link]()); //
Outputs "hello world"
• Finding a Character in a String
• The indexOf() method returns the index (the
position) of the first occurrence of a specified text
in a string (including whitespace):
• String txt = "Please locate where 'locate' occurs!";
• [Link]([Link]("locate")); //
Outputs 7
• Java counts positions from zero.
0 is the first position in a string, 1 is the second, 2
is the third ...
All String Methods:
• Return the first character (0) of a string:
• String myStr = "Hello";
• char result = [Link](0);
• [Link](result);
• Return the Unicode of the first character in a
string (the Unicode value of "H" is 72):
• String myStr = "Hello";
• int result = [Link](0);
• [Link](result);
String Concatenation
• The + operator can be used between strings to
combine [Link] is called concatenation:
• String firstName = "John";
• String lastName = "Doe";
• [Link](firstName + " " + lastName);
• concat() method to concatenate two strings:
• String firstName = "John ";
• String lastName = "Doe";
• [Link]([Link](lastName));
Adding Numbers and Strings
• Java uses the + operator for both addition and
concatenation.
• Numbers are added. Strings are concatenated.
• If you add two numbers, the result will be a
number:
• int x = 10;
• int y = 20;
• int z = x + y; // z will be 30 (an integer/number)
• If you add two strings, the result will be a string
concatenation:
• String x = "10";
• String y = "20";
• String z = x + y; // z will be 1020 (a String)
• If you add a number and a string, the result will
be a string concatenation:
• String x = "10";
• int y = 20;
• String z = x + y; // z will be 1020 (a String)
Strings - Special Characters

• As strings must be written within quotes, Java


will misunderstand this string, and generate
an error:
• String txt = "We are the so-called "Vikings"
from the north.";
• The solution to avoid this problem, is to use
the backslash escape character.
• The backslash (\) escape character turns
special characters into string characters:
The sequence \" inserts a double quote in a string:

String txt = “College of Engineering Pune is now \“COEPTECH\" University.";

The sequence \' inserts a single quote in a string:

String txt = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:

String txt = "The character \\ is called backslash.";


Other common escape sequences that
are valid in Java are:
String Buffer Class in Java
• In Java, String Buffer is a class used to create mutable (modifiable) string objects.
• Unlike the String class, which creates immutable strings, String Buffer allows modification of strings
without creating a new object each time a change is made.
• This makes it more efficient when frequent modifications are needed.
Characteristics of StringBuffer
• Mutable: Unlike String, the contents of
StringBuffer can be changed.
• Synchronized (Thread-safe): StringBuffer methods
are synchronized, making it safe for use in multi-
threaded environments.
• Performance: Slower than StringBuilder due to
synchronization but faster than String when
performing multiple modifications.
• Resizable: It expands dynamically when required.
Creating a String Buffer Object
• creating a String Buffer object using different
constructors:
• Default Constructor: Creates an empty
StringBuffer with an initial capacity of 16
characters
• StringBuffer sb = new StringBuffer();
• Parameterized Constructor: Creates a
StringBuffer with an initial string.
• StringBuffer sb = new StringBuffer("Hello");
Method Description
• Constructor with Capacity append(String str) Appends a string at the end

insert(int offset, String str) Inserts a string at the specified position


• Creates a StringBuffer with a specified
capacity.
replace(int start, int end, String str) Replaces a portion of the string

Deletes characters between specified


delete(int start, int end)
• StringBuffer sb = new StringBuffer(50); indices
reverse() Reverses the characters in the buffer

• Common Methods of StringBuffer------ length()


capacity()
Returns the length of the string
Returns the buffer’s capacity
------->>
setCharAt(int index, char ch) Modifies a character at the specified index

Ensures the buffer has at least the


ensureCapacity(int minCapacity)
specified capacity
Example Usage of StringBuffer

• public class StringBufferExample {


• public static void main(String[] args) {
• // Creating a StringBuffer object
• StringBuffer sb = new StringBuffer("Hello");
• // Append method
• [Link](" World");
• [Link]("After append: " + sb);

• // Insert method
• [Link](5, " Java");
• [Link]("After insert: " + sb);

• // Replace method
• [Link](6, 10, "C++");
• [Link]("After replace: " + sb);
• // Delete method
• [Link](6, 9);
• [Link]("After delete: " + sb);
• // Reverse method
• [Link]();
• [Link]("After reverse: " + sb);
• // Length and Capacity
• [Link]("Length: " + [Link]());
• [Link]("Capacity: " + [Link]());
• }
• }
String vs. StringBuffer vs. StringBuilder

Feature String StringBuffer StringBuilder


Mutability Immutable Mutable Mutable
Thread Safety Thread-safe (Immutable) Thread-safe (Synchronized) Not thread-safe
Slow (New object on
Performance Faster than String Fastest
modification)

When high performance is


Use Case When immutability is needed When thread safety is required needed in a single-threaded
environment
When to Use StringBuffer?

 When you need to modify a string frequently.

 When you are working in a multi-threaded environment and require thread safety.

 When performance is a concern and String Builder cannot be used due to thread safety requirements.

• Conclusion
• The String Buffer class is useful when dealing with string modifications in multi-threaded environments.
• If synchronization is not required, StringBuilder is a better alternative because it is faster.
• However, for immutable data, String should be used.
• public class String Example
• {
• public static void main(String[] args)
• {
• String str = "Hello";
• str = str + " World";
• // Creates a new object instead of modifying existing one
• [Link](str);
• // Output: Hello World
• }
• }
• Each modification creates a new object, which can lead to memory
wastage.
• Best for constant or unchanging strings.
• public class String BufferExample
• {
• public static void main(String[] args)
• {
• StringBuffer sb = new StringBuffer("Hello"); [Link]("
World");
• // Modifies the same object
• [Link](sb);
• // Output: Hello World
• }
• }
• Thread-safe (synchronized methods) but slower than StringBuilder.
• Preferred when working in multi-threaded environments.
• public class StringBuilderExample
• {
• public static void main(String[] args)
• {
• StringBuilder sb = new StringBuilder("Hello"); [Link]("
World");
• // Modifies the same object
• [Link](sb);
• // Output: Hello World
• }
• }
• Fastest performance compared to String and StringBuffer.
• Not thread-safe (Use only in single-threaded environments).
Use Case Best Choice
Constant or unchanging strings String
Modifiable strings in a multi- StringBuffer
threaded environment
Fast modifications in a single- StringBuilder
threaded environment

• Use String when immutability is required.


• Use StringBuffer when you need thread safety.
• Use StringBuilder when performance is
important in a single-threaded application.
Vectors in Java
• A Vector in Java is a dynamic array that can grow or shrink in size.
• It is part of the [Link] package and provides a way to store objects dynamically.
• The Vector class implements the List interface, making it a part of the Java Collection Framework (JCF).
 Features of Vectors:
 Dynamic Size: Unlike arrays, which have a fixed size, vectors automatically expand when more elements are added.

 Thread-Safety: Methods in the Vector class are synchronized, making it thread-safe but slower compared to ArrayList in a
single-threaded environment.

 Allows Duplicates: Vectors allow duplicate elements, similar to lists.

 Maintains Insertion Order: The order in which elements are inserted is maintained.

 Implements List and RandomAccess Interface: Supports indexed element access.


Creating a Vector

• To use a Vector, you need to import the [Link] package:

• import [Link];

• Then, you can create a Vector instance:

• Vector<Integer> vector = new Vector<>();

• You can also specify the initial capacity and capacity increment:

• Vector<Integer> vector = new Vector<>(10, 5); // Initial capacity: 10, Increments by 5


Common Methods in Vector Class

Method Description
add(E e) Adds an element to the vector
add(int index, E e) Adds an element at a specific index
remove(Object o) Removes the first occurrence of the specified element
remove(int index) Removes the element at the specified index
size() Returns the number of elements in the vector
get(int index) Retrieves the element at the specified index
set(int index, E e) Replaces the element at the specified index
isEmpty() Checks if the vector is empty
contains(Object o) Checks if the vector contains the specified element
clear() Removes all elements from the vector
Example Usage of Vector

• import [Link];
• public class VectorExample {
• public static void main(String[] args) {
• Vector<String> fruits = new Vector<>();
• // Adding elements
• [Link]("Apple");
• [Link]("Banana");
• [Link]("Mango");
• // Inserting at index
• [Link](1, "Orange");

• // Display elements

• [Link]("Vector elements: " + fruits);


• // Accessing an element

• [Link]("Element at index 2: " + [Link](2));

• // Removing an element

• [Link]("Banana");
• // Checking if vector contains an element

• [Link]("Contains Mango? " + [Link]("Mango"));

• // Display size of vector

• [Link]("Vector size: " + [Link]());


• }

• }
Vector vs. ArrayList

Feature Vector ArrayList


Synchronized (Thread-
Synchronization Not synchronized
safe)
Slower due to
Performance Faster
synchronization
Doubles capacity when
Growth Increases by 50%
needed
Suitable for multi- Better for single-
Use Case
threading threaded applications
When to Use Vectors?
 When working in multi-threaded environments where thread safety is required.

 When you need a dynamic array that can grow automatically.

 Conclusion:
• Vectors in Java provide a thread-safe, dynamically resizable alternative to arrays.
• However, they come with a performance trade-off compared to ArrayList due to synchronization.
• In modern Java applications, unless thread safety is required, ArrayList is usually preferred over Vector.

You might also like