Java 1
Java 1
1. Local Variables
• Lifecycle: Created at declaration and destroyed when the block exits or function call returns.
2. Instance Variables
• Lifecycle: Created when an object is instantiated and destroyed when the object is
destroyed.
• Access Specifiers: Can have access specifiers; if none is specified, the default access specifier
is used.
• Initialization: Not mandatory; default values depend on the data type (e.g., null for String, 0
for int).
3. Static Variables
• Definition: Also called class variables, declared using the static keyword outside methods,
constructors, or blocks.
• Single Copy Per Class: Only one copy exists per class, shared among all objects.
• Initialization: Not mandatory; default values depend on the data type (e.g., null for String, 0
for int).
• Accessing:
o Using an object: Compiler warns but replaces the object name with the class name.
• Restrictions:
Data Types:
A variable stores data to specify which type of data variable will store then we have to give data type
to variable. They are categorized into:
• Primitive Data Types: Includes boolean, char, int, short, byte, long, float, and double.
(Boolean with uppercase is a wrapper class for boolean.)
• Non-Primitive (Object) Data Types: Includes String, Array, and other objects.
Literals:
Literals are constant values assigned to variables in Java. They represent boolean, numeric, character,
or string data and serve as fixed values in a program.
Automatic conversion (Implicit conversion) happens when a smaller data type is converted into a
larger data type automatically (no data loss).
Explicit conversion happens when we manually convert a larger data type into a smaller one
using casting.
This may cause data loss because the smaller type cannot hold all the values of the larger type.
5 << >> >>> Bitwise Left Shift, Right Shift, Unsigned Right Shift Left to Right
6 < <= > >= Relational Operators and instanceof Left to Right
instanceof
10 ` ` Bitwise OR
Bitwise Operators:
1. Bitwise OR (|):
This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e., if either
of the bits is 1, it gives 1, else it shows 0.
Example:
0101
| 0111
________
This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values, i.e., if
both bits are 1, it gives 1, else it shows 0.
Example:
0101
& 0111
________
This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values, i.e., if
corresponding bits are different, it gives 1, else it shows 0.
Example:
0101
^ 0111
________
This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement representation of
the input value, i.e., with all bits inverted, which means it makes every 0 to 1, and every 1 to 0.
Example:
~ 00000101
________
Shift operators in Java move bits left or right within a binary number. These operators help with fast
multiplication, division, and bitwise manipulations.
This operator shifts the bits of a number to the left by a specified number of positions.
Example:
<< 2
---------------
This operator shifts the bits of a number to the right by a specified number of positions, while
preserving the sign bit (MSB).
Example:
>> 2
---------------
This operator shifts the bits of a number to the right, filling with 0s (ignoring the sign bit).
Example:
1111 1111 1111 1111 1111 1111 1111 0100 (-20 in binary)
>>> 2
-----------------------------------------------------
0011 1111 1111 1111 1111 1111 1111 1101 (1073741819 in decimal)
Ternary Operator:
Switch (day){
Class Syntax:
class Calculator {
int a;
public int add() {
To use this class we need to make object of this class inside main method.
Calc.add();
Method Overloading:
return n1+n2+n3;
It is a feature that allows a class to have more than one method with the
same name, as long as their parameter lists are different. This can be
1. Inside JVM in memory level memory is categorized into 2 parts that are
6. And second sections of object has methods declaration but it only have
definition of it. But the actual memory area used by methods will be be of stack.
7. This particular object will also have its own address Eg. 101 and this address
Array:
Multidimensional array:
Syntax:
For(int i=0;i<3;i++){
For(int j=0;j<4;j++){
Soutln();
For(int i=0;i<nums.length;i++){
Soutln();
Drawbacks of Array:
Note- array is an object it is created inside heap memory.
Drawbacks:
i. Fixed in size
Array of objects:
Class student {
Int rollno;
String name;
int marks;
Students[0] = s1;
Students[1] = s1;
Students[2] = s1;
1. This loop only work for array and array type data.
Sout (n);
Strings:
1. It is not a primitive data type but is a class.
We can also create String like this String = “Umar”; // behind the scene
it creates an object
Name = name+”khan”;
Sout(“Good morning”+name);
But we have not changed the existing string that is from Umar to Umar khan.
String s1 = “Zohair”;
String s2 = “Zohair”; // here we have only create one object for s1 and s2
Now “Umar”is constant for name, we cannot change the value of name variable.
String Buffer:
Sout(sb capacity());
Output: 16
Output: 20
2. String buffer give a buffer size of 16 bytes because it stored Umar and give
me 16 bytes space extra. To reduce the reallocation of string it give 16 bytes space extra.
String str = sb; // can’t assign string buffer variable to string variable.
Sb.deleteCharAt(2);
Sb.insert(0,”Java”);
Static keyword:
all object of the class. If one object changes this static variable then
String brand;
int price;
sout(brand+":"+price+":"+name);
obj1.brand = "Apple";
obj1.price = 1500;
Static Methods:
1. when we have to use instance method of a class we first have to make its object.
2. We can call static methods directly with the help of class name without creating class object.
3. We can use a static variable inside a static method but not use non-static variable.
4. But we can use non static variable indirectly with the help of by passing
sout(obj.brand+":"+obj.price+":");
Mobile.show(obj1);
5. If we make main() as non static then we have to make object of class of main() to
use main(). Since main() itself is a starting point of execution, if execution is not
started how can we create object of main()'s class. That's why we make main
method as static.
Static Block:
String brand;
int price;
public Mobile(){
price = 200;
name = "phone";
}
2. But name here is a common (static) variable to all objects. While creating
objects every time all variables along with static variable (name) will be
String brand;
int price;
public Mobile(){
price = 200;
4. If we don't construct object it will not call static block. (Will not load class)
3. A java program file at most can have only one public class.
4. If in a class there is no main method than it will not run independently but
give error.
5. If there are 4 classes in a file and each class contains main method
And all classes are set as default then after compiling there will be
4 .class files as the name of classes which having main method. Now to run them
We have to specify by their name eg. Java A, Java B etc.
1. If we are going to compile above code then we will get error because arraylist
Package in Java:
Developers can easily modify or extend a specific module without affecting the entire project.
Improves code reusability by allowing different parts of a project to use shared utility packages.
3. Security
Packages help control access to classes, preventing unauthorized access to sensitive parts of a
program.
Using access modifiers (private, protected, public, default), developers can restrict access to specific
classes and methods.
Private, protected and static, public, default, abstract, final and strictfp (basic one)
Abstract Methods:
1. We can only made abstract class and method but not variables etc.
Declare method.
Abstract Class:
than methods.
2. If a class not contains any abstract class still we can make it abstract class.
3. There is abstract class Test and have two abstract methods m1() and m2().
5. Then this child class also must have to be abstract class and for m2()
1. Public: If member and class are public then we can axcces member
3. Private: If the member is private then we can only access it within the
same class.
5. Parent class reference variable can hold object of its child class but only in same package.
a.m1();
6. For child class in other package we must use child class reference variable.
b.m1();
Interface:
Interface Implementation:
void m1();
void m2();
9. A class can implements more than one interface but not inherit
Class Object
An example of class can be a car. Objects of the class car can be BMW,
Mercedes, Ferrari, etc.
Note- In java we can create objects by using new keyword, newInstance(), clone(), deserialization,
factory methods. But most of time we use new keyword.
2. Modifiers for constructor are public, private, default and protected. A private
object's reference.
5. Need of constructor, they are used to initialize objects while creating them.
Types of constructor:
Note: Constructor and private members can not be inherited from parent class using
inheritance.
Note: Object class is the parent class of all classes in java. Object class
Advantage of Relationship:
1. Code reusability
2. Cost cutting
3. Reduce redundancy
1. Inheritance(Is-A): Using inheritance classes become tightly coupled, means if I change one
class
2. Association(Has-A):
String name;
int rollno;
}
Class car{
Car HAS-A Engine, in this method these two classes are not tightly coupled.
i. Aggregation:
• In Aggregation, both entries can survive individually which means ending one entity will not
affect the other.
ii. Composition:
Composition is a restricted form of Aggregation in which two entities are highly dependent on
each other.
• When there is a composition between two entities, the composed object cannot exist
without the other entity.
Polymorphism: Polymorphism in Java is the ability of a method to take on many forms. It allows
methods to behave differently based on the object that is calling them or based on the parameters
passed to them.
Types:
Method Overloading:
class Test{
void show(){
sout("1");
void show(){
sout("2");
class Test{
void show(){
sout("1");
Questions:
1. Can we achieve Method Overloading by changing the return type of method only?
In java, method overloading is not possible by changing the return type only because of ambiguity.
Yes we can have any number of main methods in a class by method overloading. This is because JVM
always calls main() method which receives string array as arguments only.
Case 1:
class Test{
sout("int method");
This is called automatic promotion: One type is promoted to another implicitly if no matching
datatype is found. Below is diagram.
Case 2:
class Test{
sout("object method");
t.show('h'); // it will call object method as it automatically promotes to object as it is parent class of
all classes in java.
Note: While resolving Overloading Methods, compiler will always give precedence for child type
argument than compared with parent type argument.
Case 3:
class Test{
sout("stringbuffer method");
t.show(null); // here compiler will confuse because of ambiguity error as both String and StringBuffer
are sub classes of Object
}
Case 4:
class Test{
t.show(10, 20); // will give ambiguos error as int will promote to float
Case 5:
class Test{
sout("int method");
t.show(5, 32, 14); // here it will call varargs method as varargs can take 0 to multiple arguments
Method Overriding:
class Test{
void show(){
sout("1");
void show(){
sout("2");
x.show(); //output : 2
t.show(); //output : 1
Case 1:
From Java 5.0 onwards it is possible to have different return type for a overriding method in child
class, but child's return type should be sub-type of parent's return type. This is called as covariant
return type.
Case 2:
Case 3:
Below are two rules to note when overriding methods related to exception handling-
Rule 1: If the super class overridden method does not throws an exception, subclass overriding
method can only throws the unchecked exception, throwing checked exception will lead to compile
time error.
Rule 2: If the super class overridden method does throws an exception, subclass overriding method
can only throw same, subclass exception. Throwing parent exception in Exception hierarchy will lead
to compile time error. Also there is no issue if subclass overridden method is not throwing any
exception.
Case 4:
Abstract methods in an interface or abstract class are meant to be overridden in derived concrete
classes otherwise compile-time error will be thrown.
Case 5:
We can call parent class method in overriding method using super keyword.
Case 6:
Case 7:
The presence of synchronized/strictfp modifier with method have no effect on the rules of
overriding, i.e. it's possible that a synchronized/strictfp method can overrode a non
synchronized/strictfp one and vice-versa.
Abstraction: Abstraction is hiding internal implementation and just highlighting the setup services
that we are offering.
• A abstract method must always be declared in an abstract class, or we can say that if a class
has an abstract method, it should be declared abstract as well and abstract class can have
100% concrete method and 100% abstract method.
• If a regular class extends an abstract class, then the class must have to implement all the
abstract methods of abstract parent class or it has to be declared abstract as well.
• We can not create object of abstract class but can create reference.
int no_of_tyres;
void start(){
void start(){
Interface: Interfaces are similar to Abstract class but having all the methods of abstract type except
java 8,9.
Use of Interface:
Syntax:
Interface InterfaceName{
Interface Test{
void show();
sout("1");
}
Interface Inter1{
void show();
Interface Inter2{
void display();
sout("1");
sout("2");
t.show();
t.display();
Encapsulation: Encapsulation in java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit.
• Provide public setter and getter methods to modify and view the variables values.
Class Employee{
// verification
emp_id = emp_id1;
// verification
return emp_id;
Class Company{
e.setEmpId(101);
sout(e.getEmpId());
this Keyword: this keyword is a reference variable of object and when it is used with a variable (if
declared inside class) it helps us to use instance variable of the class inside methods.
class Test{
int i;
this.i = i;
class Xyz{
t.setValues(21);
class ThisDemo{
void display(){
sout("1");
void show(){
display(); // compiler automatically adds this keyword while invoking the method. Eg:
this.display();
td.show(); // output: 1
class ThisDemo{
ThisDemo(){
ThisDemo(int a){
sout("parametrised constructor");
class ThisDemo{
sout("inside m1 method");
}
void m2(){
m1(this);
Class Test{
Test(ThisDemo td){
class ThisDemo{
void m1(){
• This keyword can be used to return the current class instance from the method.
class ThisDemo{
ThisDemo m1(){
return this;
super keyword: super keyword is a reference variable which is used to refer parent class object.
class A{
int a = 10;
class B extends A{
int a = 20;
sout(a); // output: 30
sout(this.a); // output: 20
sout(super.a); // output: 10
ob1.show(30);
• Super keyword can be used to invoke parent class constructor. // weather I put super();
inside class B constructor body or not it is automatically put.
final keyword: We can use final keyword only with variables, methods and classes.
• If we create any final variable, it becomes constant, we cannot change the value of final
variable. // final int i = 10;
**// need to re study static keyword and Strings from smart programming //**
Exception Handling:
An exception is an unwanted or unexpected event which occurs during the execution of a program
i.e. at run time, that disrupts the normal flow of the program.
class Test{
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.out.println("6");
System.out.println("7");
System.out.println("8");
Exception Error
• Runtime Exceptions or
Unchecked Exceptions
Exception Hierarchy:
Exception, then the method must either the unchecked exceptions thrown by its
handle the implementation. Generally, such methods
almost always do not declare them, as well.
Exception or it must specify the exception
using throw keyword.
try, catch:
class Test{
Whenever there is exception, the method in which exception occurs will create an object and that
object will store three things:
As exception object is created then it is passed to the JVM, JVM check it weather it is handling this
exception, if not then JVM will pass this object to default exception handler. Now default exception
handler will print that exception but before object is passed to default exception handler JVM will
abnormally terminate our program.
But I don't that my program terminates abnormally to do this I will have to manually handle our
exceptions.
Try {
// risky code
Catch(ExceptionClassName reference){
// handling code
Eg.
class Test{
try{
c=a/b;
}
catch(ArithemeticException e){ // We can also write Exception in place of ArithemeticException
If no exception is found in try block then catch block is not executed. If exception is found in try
block, it will not execute the lines below to exception causing line and will directly go to the catch
block.
finally:
finally is the block that is always executed whether exception is handled(catch) or not, whether
exception is thrown or not. Normal flow to use finally block is try-> catch->finally or it can be try->
finally. But in case try-> finally if exception occurs inside try block then it is not handled. We can't use
finally block alone means without try.
try{
c = a/b;
sout(c);
catch(ArithemetiException e){
sout(e);
finally{
}
• We can also use try and catch inside finally block.
• We can use multiple catch blocks with one try block but we can only use single finally block
with one try block, not multiple.
• If I use jump statements like return, break or continue in try block, the finally block will still
be executed.
• Resource Management: Use the finally block to close resources like files, database
connections, or network sockets to avoid resource leaks.
• Avoid Return Statements: Avoid placing return statements in the finally block, as it can
obscure the flow of the program and make it harder to understand.
• Nested Try-Finally: When working with multiple resources, consider using nested try-finally
blocks to ensure each resource is properly closed.
finalize method(): The finalize() method is called by the Garbage Collector just before an
object is removed from memory. It allows us to perform clean up activity. Once the finalized method
completes, Garbage Collector destroys that object.finalize method is present in the Object class.
Note: finalize() is deprecated in Java 9 and should not be used in modern applications. It’s
better to use try-with-resources or other cleanup mechanisms instead of relying on finalize().
Eg.
import java.util.*;
g = null;
System.gc();
try {
Thread.sleep(1000);
catch (InterruptedException e) {
e.printStackTrace();
Link: https://medium.com/@rushilakade66/various-possible-combinations-of-try-catch-finally-
5e495667880e
throw keyword:
YoungerAgeException(String msg){
super(msg);
class voting{
if(age<18){
else{sout("Vote Successfully");}
}
• We can throw either checked or unchecked exception but throw is best for customized
exception.
• We cannot write any statement after throw, otherwise it will provide unreachable statement
error.
throws keyword: throws keyword is used to declare an exception. It gives an information to the
caller method that there may occur an exception so it is better for the caller method to provide the
exception handling code so that normal flow can be maintained.
class Test{
try{
rw.ReadAndWrite();
catch(FileNotFoundException e){
e.printstackTrace();
sout("hey");
Throws keyword is used to declare only for the checked exceptions. If there occurs any unchecked
exception such as NullPointerException, it is programmers fault that he is not performing check up
before the code being used.
throw keyword throws keyword
6. We cannot write any 6.throws keyword does not have any such rule
statement after throw statement.
keyword and thus it can be
used to break the
statement.
Custom Exception:
UnderAgeException(){
class Voting{
if(age<18){
catch(UnderAgeException e){
e.printstackTrace();
UnderAgeException(){
class Voting{
if(age<18){
throw new Exception UnderAgeException(); //will be compiled but not handle exception
Non-primitive data types, also known as reference types, are types in programming languages like
Java that are not predefined by the language. Instead, they are created by the programmer or are
part of the Java library.
They store references (addresses) to memory locations where the actual data is kept, not the data
itself. Java library comes with JRE.
What is a Primitive Data Type?
A primitive data type is a basic built-in data type provided directly by the programming language to
represent simple values. Primitive data types are language-level features built into the Java compiler.
String:
String is a non-primitive datatype. String is the sequence of characters. String is a final class.
public final class String extends Object implements CharSequence, Serializable, Comparable{ }
• We can create object of String class- String s = new String("abc"); // this creates immutable
object.
String Constant Pool: The String Constant Pool (SCP), also known as the String Intern Pool, is a
special memory area within the Java Heap that stores string literals. It is a mechanism used by the
Java Virtual Machine (JVM) to optimize memory usage and improve performance when working with
strings.
• String s1 = new String("Coffee"); By writing this will create two objects one in the heap
memory and s1 will refer to this object which is in the heap and other will be created in the
String Constant pool for storing string literals and JVM will internally create reference for the
object in the String constant pool.
• String s2 = "Tea"; This will create only one object in the String constant pool for String
literal(Tea) and s2 will refer to this object. The String objects present in String
constant pool are not applicable for Garbage Collection because a reference variable
internally is maintained by JVM.
• Now if i String s3 = new String("Coffee"); This will create an object in the heap memory
and s3 will refer to this object in heap, but not any object in the String constant pool will be
created because there is already an object for same String literal(Coffee).
• Now String s4 = "Coffee"; this will create no any object as there is already an object for
the same literal, but s4 will refer to the same object in the String Constant pool, not
internally created by JVM.
• Now String s5 = "Tea" This will also create no any object and s5 will also refer to same
object for literal Tea in the String constant pool.
Strings Are Immutable: String is immutable that is Strings objects are immutable. It means once
String object is created, its data or state can't be changed but a new String object is created.
Eg. * String s = new String(Coffee); // this will create two objects one in the heap and other in
the SCP.
s.concat("Tea"); // this will not change the heap object to which s is referring but it will create
a new object having CoffeeTea, and it will also create an object in SCP for Tea
literal as was not already present. But
S still will have Coffee to change it to CoffeeTea we have to do this- s = s.concat("Tea"); now s is no
longer pointing to Coffee.
* String s1 = "Pen"; // this will create a literal object in the SCP if not already there for this.
now s1 = s1.concat("Paper"); // this will create another object for Paper literal in SCP and a
object in the heap for PenPaper, s1 is now referring to PenPaper not Pen.
But now I want to change value of city3 to Lucknow, if String was mutable then value of city2, city3
will also be changed but I only wished to change city3. That’s why the String object in SCP will not
change but another Literal object will be created for Lucknow and now city3 will refer to this object.
Strings are immutable so that shared literals in the String Constant Pool remain safe and unchanged.
String class has got special features which is not available to other java classes and making the String
class final prevents subclasses that could break these assumptions.
• String Constant Pool (SCP) :- It is special memory location in heap area which stores String
Literals.
• Immutable Objects :- The String objects are immutable which means once String object is
created its data or state can't be changed but a new string object is created.
• Security:- The parameters used for network connections, database connection URLs,
usernames/ passwords, etc are represented in Strings. If it was mutable, these parameters
could be changed easily.
• Class loading:- String is used as an arguments for class loading. If mutable, it could result in
the wrong class being loaded (because mutable objects change their state).
• Memory management :- When compiler optimizes our String objects, it seems that if two
objects have the same value (a = " test", and b = " test") and thus we need only one string
object (for both a and b, these two will point to the same object).
Final vs Immutable: final is the keyword used with class, methods and variables but immutability is
the concept used for objects in which object state and content cannot be changed.
• Object class equals() is used to compare references(address) comparison now String class
inherit Object class and override equals(). String class equals() is used for content
comparison of Strings.
String Constructors:
i. String(){ }
vi. public String(byte[] b){ } // let say byte[] b = {101,102,103}; it will convert to char like a,b,c
In Java, a `char[]` (character array) is preferred over `String` for storing passwords because `String` is
immutable, which means once it is created, it cannot be changed or erased from memory until Java’s
garbage collector removes it. This can be risky because the password might stay in memory for a long
time, and someone could access it by scanning memory. On the other hand, a `char[]` is mutable, so
we can manually clear the password from memory by replacing its characters (like using
`Arrays.fill()`), making it safer for storing sensitive data like passwords.
+ operator:
String s1 = "Pen";
String s2 = "Paper";
Sout(s1+s2); output: PenPaper // but a new object will be create in heap memory
This method method of String class is included in java String since JDK 1.6, this method returns true if
String is empty. But if String is provided null, this method will throw null pointer exception.
Length method counts the number of characters in the String and returns it in integer. This method
returns the length of any String which is equal to the number of 16-bit Unicode characters in the
String. But if String is provided null, this method will also throw null pointer exception.
This method removes spaces before the first and after the last character of the String, it does not
removes space between the middle of String. If String only contains spaces it will remove them too.
But if String is provided null, this method will also throw null pointer exception.
This method compares the content of given two Strings if ant character is not matched , it returns
false, if all characters are matched it returns true. Eg. s1.equals(s2);
This method is used for comparing two Strings lexicographically. Each character of both Strings is
converted into a Unicode(decimal) value for comparison. If both are equal, it returns 0 else it returns
positive for large String and negative for small String. Eg. s1.compareTo(s2);
The method compareToIgnoreCase() compares two strings just like compareTo() but it ignores case
i.e. it treats uppercase and lowercase letters as the same.
This method is used to combine multiple strings into one string with a delimiter (like a space,
comma, dash, etc.) in between. We can not use null as delimiter otherwise it will give null pointer
exception Syntax: String.join(CharSequence delimiter, CharSequence... elements)
This method starts with the char value at thespecified index and ends with the char value at (end-1).
It throws java.langStringIndexOutOfBoundException if any index position value is negative.
Eg. s.subSequence(3,9);
This method returns a new String that is a substring of this String. The substring begins at the
specified beginIndex and extends to the character at index endIndex-1. It throws
java.langStringIndexOutOfBoundException if any index position value is negative.
This method returns a String replacing all the old characters or CharSequence to new characters or
CharSequence. This method was introduced in JDK 1.5 version.
This method replaces all the substrings that fits the specified regular expression with the
replacement String. If the specified regular expression(regex) is not valid, it will provide
java.util.regex.PatternSyntaxException.
This method returns the position of the first occurrence of specified character int a String or return -
1 if the character does not occur.
This method returns the position of the last occurrence of the specified character in a String or
return -1 if the character does not occur.
This method returns the charater at the specified index. But index value should lie between 0 and
length()-1.
Eg. s.charAt(3);
This method searches the sequence of characters in the given String. It returns true if sequence of
char values are found in this String otherwise returns false.
Eg. s.contains("ep");
This method checks if a String starts with the specified prefix from 1st index. If yes it will return true
else false.
Eg. s.startsWith("d");
This method checks whether the String ends with a specified suffix. If yes , then method will return
true else flase. Eg. s.endsWith("d");
Eg. s.toUpperCase();
This methods converts all characters of the String into a lowercase letter.
Eg. s.toLowerCase();
This is an static method that converts different types of values into String, we can convert int, long,
float, double, object and any other type into String.
Eg. String.valueOf(21);
This method converts the given String into a sequence of characters. The returned array length is
equal to the length of the String.
Eg. s.toCharArray();
StringBuffer: StringBuffer is a class in Java used to create mutable Strings that means you can
change(modify) the String without creating a new object.
sb.append("abc"); this will change String to xyzabc without creating new object.
If the data does not change or change one or two times only, use String. If data is constantly or
frequently changing like in calculatorn, notepad etc, we should use StringBuffer. It is inside the
java.lang package.
StringBuffer Constructors:
The capacity() method returns the total number of characters a StringBuffer can store before needing
to resize its internal memory. Java gives a default capacity of 16 characters when you create an
empty StringBuffer. If the number of characters exceeds the current capacity, Java increases it
automatically using this formula:newCapacity = (oldCapacity × 2) + 2
Eg. sb.capacity();
The append() method is used to add text (or other values) to the end of an existing StringBuffer
object. It modifies the original buffer — so no new object is created like in String.
sb.append(123); // int
sb.append(45.67); // double
sb.append(true); // boolean
sb.append('!'); // char
The length() method returns the number of characters currently stored in the StringBuffer.
Eg. sb.length();
The charAt() method is used to get a single character from a string (or StringBuffer) at a specific
index. If you use an invalid index (like negative or too large), it throws:
StringIndexOutOfBoundsException
Eg. stringBuffer.charAt(index);
This method removes a part of the text from the StringBuffer, starting at the start index and ending
before the end index. If you use an invalid index (like negative or too large), it throws:
StringIndexOutOfBoundsException
Eg. sb.delete(2, 5);
Similar to delete() but removes the character at the specified index from the StringBuffer.
Eg. sb.deleteCharAt(4);
StringBuffer inherits the equals() method from the Object class but
This method returns the position of the first occurrence of specified character int a StringBuffer or
return -1 if the character does not occur.
Eg. Sb.indexOf("c");
This method returns the position of the last occurrence of the specified character in a StringBuffer or
return -1 if the character does not occur.
The insert() method adds text or values at a specific position (index) inside a StringBuffer.
Eg. sb.insert(index, value); You can insert:String, char, int, boolean, float, double, long, char[],
Object.
The replace() method in StringBuffer replaces characters between the specified start and end indexes
with the provided new string.
The reverse() method reverses the characters in the StringBuffer and modifies the original buffer.
Eg. sb.reverse();
The subSequence(int start, int end) method returns a portion of the string, starting from index start
to end - 1`.
Eg. sb.subSequence(3,6);
The toString() method returns the current content of the StringBuffer as a String object.
16. ensureCapacity() output: void(does not return)
The ensureCapacity() method is used to increase the internal buffer size (capacity) of a StringBuffer if
needed.
The setCharAt(int index, char c) method replaces the character at the specified index with the new
character c.
Expands the content and fills the extra characters with null characters (\u0000) if newLength is more
than the current length.
The trimToSize() method reduces the capacity of a StringBuffer to match its current length.
StringBuilder: StringBuilder is a mutable sequence of characters meaning you can change its content
without creating a new object every time. It's like StringBuffer, but with no thread safety, making it
faster in single-threaded environments.
StringBuilder constructors same as StringBuffer constructors and methods also but methods are non-
syncrhonized.
Multithreading:
Process Thread
3. Process takes more time for 3. Thread takes less time for
context switching. context switching.
9. Process require more time for 1. Thread require less time for
termination. termination.