0% found this document useful (0 votes)
10 views57 pages

Java 1

The document provides an overview of variables in Java, detailing local, instance, and static variables, along with their lifecycles, scopes, and access methods. It also covers data types, type conversion, operators, and memory management, including stack and heap distinctions. Additionally, it explains arrays, strings, and the use of the static keyword, emphasizing key programming concepts and examples.

Uploaded by

altamashdr14
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)
10 views57 pages

Java 1

The document provides an overview of variables in Java, detailing local, instance, and static variables, along with their lifecycles, scopes, and access methods. It also covers data types, type conversion, operators, and memory management, including stack and heap distinctions. Additionally, it explains arrays, strings, and the use of the static keyword, emphasizing key programming concepts and examples.

Uploaded by

altamashdr14
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
You are on page 1/ 57

Variables: A variable is like a container that stores data.

Eg: int age = 27;

1. Local Variables

• Definition: Declared inside a block, method, or constructor.

• Lifecycle: Created at declaration and destroyed when the block exits or function call returns.

• Scope: Limited to the block in which they are declared.

• Access: Cannot be accessed outside their defining block.

• Initialization: Must be explicitly initialized before use.

2. Instance Variables

• Definition: Non-static variables declared in a class but outside methods, constructors, or


blocks.

• 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).

• Scope: Available throughout the class except in static contexts.

• Access: Can only be accessed by creating an object.

• Initialization Methods: Typically initialized via constructors or instance blocks.

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.

• Lifecycle: Created at program start and destroyed at execution end.

• 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.

o Without a class name: Compiler appends the class name automatically.

o Accessing from another class: Must specify the class name.

• Restrictions:

o Cannot be declared inside instance methods.

o Can be initialized using static blocks.

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.

Primitive Data Types:


Data Description Default Size (in Example Range
Type Value bytes)

byte Stores whole 0 1 byte a = 100; -128 to 127


numbers (small
range)

short Stores whole 0 2 short b = -32,768 to 32,767


numbers 20000;
(medium range)

int Stores whole 0 4 int c = 100000; -2,147,483,648 to


numbers (large 2,147,483,647
range)

long Stores whole 0L 8 long d = -9,223,372,036,854,775,808


numbers (very 15000000000L; to
large range) 9,223,372,036,854,775,807

float Stores fractional 0.0f 4 float e = 5.75f; Approx. ±3.4E-38 to


numbers (single ±3.4E+38 (6-7 decimal
precision) places)

double Stores fractional 0.0d 8 double f = Approx. ±1.7E-308 to


numbers (double 19.99d; ±1.7E+308 (15-16 decimal
precision) places)

boolean Stores true or false 1 (not boolean g = true or false


false values precisely true;
defined)

char Stores a single \u0000 2 char h = 'A'; '\u0000' (0) to '\uffff'


character (65,535)
(Unicode)

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.

Type Conversion And Type Casting

1. Type Conversion (Widening)

Automatic conversion (Implicit conversion) happens when a smaller data type is converted into a
larger data type automatically (no data loss).

This follows the order:


int num = 100;

double d = num; // Implicit conversion (int → double)

System.out.println(num); // Output: 100

System.out.println(d); // Output: 100.0

2. Type Casting (Narrowing)

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.

This follows the order:

double num = 99.99;

int x = (int) num; // Explicit casting (double → int)

System.out.println(num); // Output: 99.99

System.out.println(x); // Output: 99 (fractional part is lost)

Java Operator Precedence Table

Precedence Operators Description Associativity

1 (Highest) () [] . Parentheses, Array Access, Member Access Left to Right

2 ++ -- + - ~ ! Post-Increment, Post-Decrement, Unary Plus, Right to Left


Unary Minus, Bitwise NOT, Logical NOT

3 */% Multiplication, Division, Modulus Left to Right

4 +- Addition, Subtraction, String Concatenation Left to Right

5 << >> >>> Bitwise Left Shift, Right Shift, Unsigned Right Shift Left to Right

6 < <= > >= Relational Operators and instanceof Left to Right
instanceof

7 == != Equality and Inequality Left to Right


8 & Bitwise AND Left to Right

9 ^ Bitwise XOR Left to Right

10 ` ` Bitwise OR

11 && Logical AND Left to Right

12 || Logical OR Left to Right

13 ?: Ternary Operator Right to Left

14 = += -= *= /= %= = <<= >>= >>>=` Assignment


&= ^= ` Operators

15 (Lowest) , Comma (Used in expressions) Left to Right

Bitwise Operators:

Now let’s look at each one of the bitwise operators in Java:

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:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7

0101

| 0111

________

0111 = 7 (In decimal)

2. Bitwise AND (&):

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:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7

0101

& 0111

________

0101 = 5 (In decimal)

3. Bitwise XOR (^) :

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:

a = 5 = 0101 (In Binary)

b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7

0101

^ 0111

________

0010 = 2 (In decimal)

4. Bitwise Complement (~):

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:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5 in java (8 bits)

~ 00000101

________

11111010 = 246 (In decimal)


Shift Operators in Java:

Shift operators in Java move bits left or right within a binary number. These operators help with fast
multiplication, division, and bitwise manipulations.

1. Left Shift (<<):

This operator shifts the bits of a number to the left by a specified number of positions.

Each left shift multiplies the number by 2^n.

The vacant positions on the right are filled with 0s.

Example:

0000 0101 (5 in binary)

<< 2

---------------

0001 0100 (20 in decimal)

2. Right Shift (>>) (Signed Shift):

This operator shifts the bits of a number to the right by a specified number of positions, while
preserving the sign bit (MSB).

Each right shift divides the number by 2^n.

Example:

0001 0100 (20 in binary)

>> 2

---------------

0000 0101 (5 in decimal)

3. Unsigned Right Shift (>>>):

This operator shifts the bits of a number to the right, filling with 0s (ignoring the sign bit).

Useful for handling large numbers and bit manipulations.

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:

Eg. Result = no%2==2? 10:20;

If the Condition is true the 10 will be in the result.

*”break” keyword is used to come out from the block.

Updated Switch Statement:

1. Here we don’t need to put break Statement simple we put arrow to

only execute the specific case.

Eg. String day = “Sunday”;

Switch (day){

Case “Saturday”, “Sunday”-> sout(“6 am”);

Case “Monday”-> sout(“8 am”);

Default -> sout(“7am”);

2. Here switch statement can return a value.

Eg. String result = “ “;

Result = switch (day) {

Case “Saturday”, “Sunday” -> “6 am”;

Case “Monday” -> “8 am”;

Default -> “7am”;

We can also use : yield for same thing.

Object & class:

1. Object have property & behaviour

2. Objects are made by JVM

Class Syntax:

class Calculator {

int a;
public int add() {

sout (“inside add”);

To use this class we need to make object of this class inside main method.

public static void main(String[ ] args) {

Calculator calc = new Calculator();

// to use the method

Calc.add();

Method Overloading:

Eg. Class calculator{

public int add(int n1, int n2, int n3) {

return n1+n2+n3;

Public int add (int n1, int n2) {

return n1+ n2;

Public double add (double n1, int n2){

return n1+ n2;

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

achieved by varying no of parameters and their types.

Stack and Heap:

1. Inside JVM in memory level memory is categorized into 2 parts that are

stack memory and Heap memory.

2. Every methods have its own stack.

3. Reference variables of objects are created in stack. And functions and

objects are created inside heap memory.


4. A object has two sections one for all variables (instance).

5. local variables are part of stack.

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

will be stored in stack.

8. We can create many objects of same class.

Array:

Multidimensional array:

Syntax:

Int nums [] [] = new int[3] [4]; // rows and columns

For(int i=0;i<3;i++){

For(int j=0;j<4;j++){

Sout(nums[i] [j]+ “ “);

Soutln();

Jagged and multidimensional array:

Int nums [] [] = new int[3] [];

Nums[0] = new int[3];

Nums[1] = new int[4];

Nums[2] = new int[2];

For(int i=0;i<nums.length;i++){

For(int j=0;j<nums[i]. length;j++){

Sout(nums[i] [j]+ “ “);

Soutln();

Drawbacks of Array:
Note- array is an object it is created inside heap memory.

Drawbacks:

i. Fixed in size

ii. It traverse between the elements for searching and inserting

iii. It can only store elements of same type.

Array of objects:

Class student {

Int rollno;

String name;

int marks;

Student s1 = new Student();

Student students[] = new Student[3];

Students[0] = s1;

Students[1] = s1;

Students[2] = s1;

For Each Loop (Enhance for loop):

1. This loop only work for array and array type data.

2. No need to know length of array.

3. It Simply iterates with array and gives value to n at time.

Eg. For (int n: nums) {

Sout (n);

Eg. For (Student stud: students) {

Sout stud: “ + stud.mark);

Strings:
1. It is not a primitive data type but is a class.

2. We can use string only with ‘+’ operator.

3. String name = new String(“Umar”);

Sout(“ Good Morning” + name);

Sout (name.charAt(1)); // know what character at index no 1

Sout (name. Concat(“knan”));

We can also create String like this String = “Umar”; // behind the scene

it creates an object

Mutable vs Immutable String:

String name = “Umar”;

Name = name+”khan”;

Sout(“Good morning”+name);

Output: Good morning Umar khan

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

4. String are constant eg: String name = “Umar”;

Now “Umar”is constant for name, we cannot change the value of name variable.

5. By default Strings are immutable.

String Buffer:

1. String buffer are mutable.

StringBuffer sb = new StringBuffer();

Sout(sb capacity());

Output: 16

StringBuffer sb = new StringBuffer(“Umar”);

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.

3. Capacity() and length() are different.

Sb.append(“khan”); // output: Umar khan

String str = sb; // can’t assign string buffer variable to string variable.

String str = sb.toString();

Sb.deleteCharAt(2);

Sb.insert(0,”Java”);

4. String buffer is thread safe and stringbuilder is not.

Static keyword:

1. We can use static keyword to make an instance variable common to

all object of the class. If one object changes this static variable then

it will be changed for all the objects of the same class.

2. Static variable is shared by all the objects.

Eg. class Mobile{

String brand;

int price;

static string name;

public void show(){

sout(brand+":"+price+":"+name);

public static void main(String[] args){

Mobile obj1 = new Mobile();

obj1.brand = "Apple";

obj1.price = 1500;

Mobile.name = "smartphone"; \\ can also use class name instead of

object in static variable.


}

3. In non-static methods we can use static variables.

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

object as parameters in static function.

Eg. public static void show(Mobile obj){

sout(obj.brand+":"+obj.price+":");

public static void main(String[] args){

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:

1. If we want to initialise the instance variables with default values we can

use constructors while creating objects.

Eg. class Mobile{

String brand;

int price;

static String name;

public Mobile(){

brand = " ";

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

initialise. To avoid static variable from initialising every time on creating

object we use static block.

Eg. class Mobile{

String brand;

int price;

static String name;

static{ name = "phone"; }

public Mobile(){

brand = " ";

price = 200;

3. Static block is called first then constructor here.

4. If we don't construct object it will not call static block. (Will not load class)

Java Source File Structure:

1. In a java program file we can have any number of classes.

2. We can name java program file to any thing if there is no any

Public class in the java program file.

3. A java program file at most can have only one public class.

and if there is a public class in the file than we must have to

name java program file to the name of that 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.

Java Source File Import Statement Introduction:

Eg. Class Test{

public static void main(String[] args){

ArrayList l = new Arraylist();

1. If we are going to compile above code then we will get error because arraylist

ss not imported , to solve this we have to import as import java.util.ArrayList;

2. There are two types of imports: 1. Explicit Import: java.util.ArrayList 2.

Implicit Import: java.util.*

3. Two types of packages we don’t need to import , as these are by default

Available - 1. java.lang 2. Default package.

4. Classes in same package not require import.

5. If I want to use Pattern class

(i) import java.*

(ii) import java.util.*

(iii) import java.util.regex.* (correct)

6. Inside a java program file only one package statement is allowed.

Package in Java:

Packages in Java are a mechanism that encapsulates a group of

similar classes, sub-packages, and interfaces.

Advantages of Packages in Java:

1. Naming Conflict Resolution

Eg. package com.companyA.utils;

public class Logger { }


package com.companyB.utils;

public class Logger { }

2. Modularity and Maintainability

Packages help break a large application into smaller, manageable modules.

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.

Class Level Modifiers:

1. We have to provide some information about class to JVM, that is,

is this class accessable from anywhere or not, object creation possible

or not. To specify these information to JVM we use corresponding modifiers.

2. For class accessability from any where we use public.

3. If it is default, then we can use this class within the package.

4. If class is abstract we can't create its object.

5. If class is final then child class creation is not possible.

6. Modifiers available for top level class are -

public, default, abstract, final and strictfp. (basic one)

7. For inner class the available modifiers are -

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.

2. Even though we don’t know about implementation but still we can

Declare method.

3. Abstract method have only declaration but no implementation.

4. Child class are responsible for to provide implementation to abstract method.

Eg. public class Vehicle{


public abstract int getNoOfWheels();

Abstract Class:

1. If we feel the implementation of the class is not complete then we

can make this class as abstract class.

2. If there is at least one abstract method in the class then we

must have to make this class as abstract.

3. We can recognize partially implemented class if it contain one or more

than methods.

4. We can't create object of abstract class.

Abstract class vs Abstract Method:

1. If a class contains at least one abstract method then compulsory

Class should be made abstract class.

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().

To provide implementation to these methods child class is responsible.

Eg. Abstract class Test{

public abstract void m1();

public abstract void m2();

public class Subtest extend Test{

public void m1(){ //implementation }

public void m2(){ //implementation }

4. Let say if we don’t have implementation to m2() in child class

5. Then this child class also must have to be abstract class and for m2()

other next level child class is responsible.

6. We can make object of child class which implements

abstract method from parent abstract class.


Member Modifiers(variables & methods):

There are 12 member modifier but we will not discuss all.

1. Public: If member and class are public then we can axcces member

From any where.

2. Default: We can access it from only within the package.

3. Private: If the member is private then we can only access it within the

same class.

4. Protected: If members are protected then it is accessable in

same package , also in child classes of other package.

5. Parent class reference variable can hold object of its child class but only in same package.

Eg. A a = new B();

a.m1();

6. For child class in other package we must use child class reference variable.

Eg. B b = new B();

b.m1();

Interface:

1. In Java, an interface is a blueprint for a class that defines a set of

methods and constants that other classes must implement.

Interfaces are similar to protocols.

2. It is any service requirement specification.

3. Contract between client and service provider is known as interface.


4. Any method in interface is by default public and abstract.

5. Interface is considered 100 percent pure abstraction.

Interface Implementation:

Eg. Interface Interf{

void m1();

void m2();

Class ServiceProvider implements Interf{

public void m1(){ // implementation }

public void m2(){ // implementation }

6. We must keep access modifier public for methods while implementing

Them in child class.

7. In implementing methods we must provide implementation to all methods

in interface or make class as abstract and remaining methods will be

Implemented by child class.

8. All variables inside interface are public static final

9. A class can implements more than one interface but not inherit

more than one abstract class.

10. We can extends interface from interface.

Object Oriented Programming System

Class Object

Class is the blueprint of an object. It is used to An object is an instance of the class.


create objects.

No memory is allocated when a class is Memory is allocated as soon as an object is


declared. created.

A class is a group of similar objects. An object is a real-world entity such as a


book, car, etc.

Class is a logical entity. An object is a physical entity.


A class can only be declared once. Objects can be created many times as per
requirement.

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.

Constructors: Constructor is a block similar to method having same name

as that of class name.

1. Constructor doesn’t have return type and void.

2. Modifiers for constructor are public, private, default and protected. A private

constructor is used in restricting object creation.

3. It executes automatically when we create an object and there is no need to make

object's reference.

4. A class can have many constructors. Execution will be decided according to

method overloading concept.

5. Need of constructor, they are used to initialize objects while creating them.

Types of constructor:

Default Constructor: is created by compiler with no arguments. But compiler

only default constructor if user doesn’t create any constructor.

No-argument Constructor: It is created by user with no arguments in it.

Parametrized-Constructor: It is user defined constructor with parameter.

Inheritance: It is the mechanism by which one class is allowed to inherit the

features(fields and methods) of another class. It is called 'is a' relationship.

Note: Constructor and private members can not be inherited from parent class using
inheritance.

Eg. class Vehicle {


protected String brand = "Ford";
public void honk() {
System.out.println("Tuut, tuut!");
}
}
class Car extends Vehicle {
private String modelName = "Mustang";
public static void main(String[] args) {
Car myCar = new Car();
myCar.honk();
System.out.println(myCar.brand + " " + myCar.modelName);
}
}

Note: Object class is the parent class of all classes in java. Object class

does not extends any other class.

Relationship between classes:

Advantage of Relationship:

1. Code reusability

2. Cost cutting

3. Reduce redundancy

Types of relationship between classes:

1. Inheritance(Is-A): Using inheritance classes become tightly coupled, means if I change one
class

Property than other is affected.

2. Association(Has-A):

Eg. Class Student{

String name;

int rollno;
}

Student HAS-A name, Student HAS-A rollno.

We can achieve association directly as we did above or by new keyword:

Eg. Class Engine{

Class car{

Engine e = new Engine();

Car HAS-A Engine, in this method these two classes are not tightly coupled.

i. Aggregation:

It is a special form of Association where:

• It represents Has-A’s relationship.

• It is a unidirectional association i.e. a one-way relationship. For example, a department can


have students but vice versa is not possible and thus unidirectional.

• 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.

• It represents part-of relationship.

• In composition, both entities are 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:

1. Compile Time Polymorphism(static Polymorphism) : Achieved by method overloading,


handled by compiler

2. Run Time Polymorphism(Dynamic Polymorphism) : Achieved by method overriding, handled


by JVM

Method Overloading:

• Methods should have same name

• Methods should be in Same class

• Different arguments : Number of arguments, sequence of arguments and type of arguments.

class Test{

void show(){

sout("1");

void show(){
sout("2");

Public static void main(String arr[]){

Test t = new Test();

t.show(); // here now the compiler will confused as it is ambiguity error

Here is correct method overloading

class Test{

void show(){

sout("1");

void show(int a){


sout(a);

Public static void main(String arr[]){


Test t = new Test();

t.show(); // here now the compiler will confused as it is ambiguity error

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.

2. Can we overload java main method?

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{

void show(int a){

sout("int method");

void show(String a){


sout("string method");

Public static void main(String arr[]){

Test t = new Test();

t.show('h'); // it will print int method but we have passed char

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{

void show(object a){

sout("object method");

void show(String a){


sout("string method");

Public static void main(String arr[]){

Test t = new Test();

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{

void show(StingBuffer a){

sout("stringbuffer method");

void show(String a){


sout("string method");

Public static void main(String arr[]){

Test t = new Test();

t.show("abc"); // calls string method

t.show(new StringBuffer("xyz); // calls 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{

void show(int a, float b){

sout("int float method");

void show(float a, int b){


sout("float int method");

public static void main(String arr[]){

Test t = new Test();

t.show(10, 20); // will give ambiguos error as int will promote to float

Case 5:

class Test{

void show(int a){

sout("int method");

void show(int… a){


sout("varargs method");

public static void main(String arr[]){

Test t = new Test();

t.show(10); // will call int method

t.show(5, 32, 14); // here it will call varargs method as varargs can take 0 to multiple arguments

Method Overriding:

• Methods should have same name.

• Methods should be in different classes.


• Same arguments: Number of arguments, sequence of arguments and type of arguments.

• There should be inheritance concept.

class Test{

void show(){

sout("1");

class Xyz extends Test{

void show(){
sout("2");

public static void main(String arr[]){

Test t = new Test();

Xyz x = new Xyz();

x.show(); //output : 2

t.show(); //output : 1

Case 1:

Do overriding method must have same return type?

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:

Access-Modifiers and Metod Overriding?


The access modifier for an overriding method can allow more, but not less, access than the
overridden method . For example, a protected instance method in the super class can be made
public, not private, in the subclass. Doing so, will generate compile-time error.

Case 3:

Overriding and Exception-Handling?

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:

Overriding and Abstract Method?

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:

Invoking overridden method from sub-class?

We can call parent class method in overriding method using super keyword.

Case 6:

Which methods cannot override?

Final methods, static methods, private methods can not be overridden.

Case 7:

Overriding and synchronized/strictfp mehod?

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.

We can achieve abstraction in java by using-

Abstract (0-100%) class and Interface (100%)

Abstract Method and Abstract class:

• A method without body (no implementation) is known as abstract method.

• 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.

abstract class Vehicle{

int no_of_tyres;

abstract void start();

class Car extends Vehicle{

void start(){

sout("starts with key");

class Scooter extends Vehicle{

void start(){

sout("starts with kick");

public static void main(String arr[]){

Car c = new Car();

c.start(); // output: starts with key

Scooter s = new Scooter();

s.start(); // output: starts with kick

Vehicle v = new Car();

v.start(); // output: starts with key


}

Interface: Interfaces are similar to Abstract class but having all the methods of abstract type except
java 8,9.

Interface is a blueprint of class, it specify what a class must do and not.

Use of Interface:

• It is used to achieve abstraction.

• It supports multi inheritance.

• It can be used to achieve loose coupling.

Syntax:

Interface InterfaceName{

abstract methods // but public and abstract

fields // but public, static, final

In java 8 version -----------------------

can have default concrete methods

can also have public static method

In java 9 version ------------------------

can have private methods

Interface Test{

void show();

Class Test2 implements Test{

public void show(){

sout("1");

public static void main(String arr[]){

Test2 t = new Test2();

}
Interface Inter1{

void show();

Interface Inter2{

void display();

Class Test2 implements Inter1, Inter2{

public void show(){

sout("1");

public void display(){

sout("2");

public static void main(String arr[]){

Test2 t = new Test2();

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.

Steps to achieve Encapsulation:

• Declare the variables of a class as private.

• Provide public setter and getter methods to modify and view the variables values.

Class Employee{

private int emp_id;

public void setEmpId(int emp_id1){

// verification
emp_id = emp_id1;

public int getEmpId(){

// verification

return emp_id;

Class Company{

public static void main(String arr[]){

Employee e = new Employee();

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;

void setValues(int i){

this.i = i;

class Xyz{

public static void main(String arr[]){

Test t = new Test();

t.setValues(21);

Uses of this keyword:

• This keyword id used to invoke current class instance variable.


• This keyword can be used to invoke current class method (implicitly).

class ThisDemo{

void display(){

sout("1");

void show(){

display(); // compiler automatically adds this keyword while invoking the method. Eg:
this.display();

public static void main(String arr[]){

ThisDemo td = new ThisDemo();

td.show(); // output: 1

• This keyword can be used to invoke current class constructor.

class ThisDemo{

ThisDemo(){

sout("no argument constructor");

ThisDemo(int a){

this(); // calls no argument constructor

sout("parametrised constructor");

public static void main(String arr[]){

ThisDemo td = new ThisDemo(10);

• This keyword can be used to pass an argument in the method call.

class ThisDemo{

void m1(ThisDemo td){

sout("inside m1 method");
}

void m2(){

m1(this);

public static void main(String arr[]){

ThisDemo td = new ThisDemo(10);

td.m2(); //output; inside m1 method

• This keyword can be used to pass as an argument in the constructor call.

Class Test{

Test(ThisDemo td){

sout("test class constructor");

class ThisDemo{

void m1(){

Test t = new Test(this);

public static void main(String arr[]){

ThisDemo td = new ThisDemo(10);

td.m1(); //output test class constructor

• This keyword can be used to return the current class instance from the method.

class ThisDemo{

ThisDemo m1(){

return this;

public static void main(String arr[]){

ThisDemo td = new ThisDemo(10);


td.m1();

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;

void show(int a){

sout(a); // output: 30

sout(this.a); // output: 20

sout(super.a); // output: 10

public static void main(String arr[]){

B ob1 = new B();

ob1.show(30);

Uses of super keyword:

• Super keyword can be used to refer parent class instance variable.

• Super keyword can be used to invoke parent class method.

• 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;

• If we make final method, it cannot be override now.

• If we make final class, it cannot be inherited now.

**// 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{

public static void main(String arr[]){

System.out.println("1");

System.out.println("2");

System.out.println("3");

System.out.println("4");

System.out.println(100/0); // Exception in this line, will only print up to 4

System.out.println("5");

System.out.println("6");

System.out.println("7");

System.out.println("8");

Exception Error

1. Exception occurs because 1. Error occurs because


of our of lack of

programs system resources

2. Exceptions are 2. Errors are not


recoverable i.e. recoverable i.e.

programmer can handle them using programmer can't handle them to

try-catch block their level

3. Exceptions are of two 3. Errors are only of one


types : type :

• Compile Time • Runtime


Exceptions or Exceptions or

Checked Exceptions Unchecked Exceptions

• Runtime Exceptions or

Unchecked Exceptions
Exception Hierarchy:

Checked Exception Unchecked Exception

1. Checked Exception are the 1. Unchecked Exception are the


exceptions that are exceptions that are not
checked at compile time.
Checked and handled at compile time.

2. The program gives a 2. The program compiles time


compilation error if a because the compiler is not
able to check the exception.
Method throws a checked exception.

3. If some code within a 3. A method is not forced by


method throws a checked compiler to declare

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.

4. A checked exception occur 4. Unchecked exception occurs


when the chances of failure mostly due to programming
are too high. mistakes.

5. They are direct subclass of 5. They are direct subclass of


Exception class but do not RuntimeException class.

inherit from RuntimeException class.

try, catch:
class Test{

public static void main(String[] args){

FileInputStream fis = FileInputStream("d:/abc.txt"); // will have compiletime exception

int a=100, b=0, c;

c=a/b; // will have arithemetic exception(a runtime exception)

How to Handle Exception:

Whenever there is exception, the method in which exception occurs will create an object and that
object will store three things:

1. Exception name 2. Description 3. Stack trace

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.

We can handle exceptions using 5 keywords:

try, catch, finally, throw, throws.

try catch syntax:

Try {

// risky code

Catch(ExceptionClassName reference){

// handling code

Eg.

class Test{

public static void main(String[] args){

int a=100, b=0, c;

try{

c=a/b;

}
catch(ArithemeticException e){ // We can also write Exception in place of ArithemeticException

sout("can’t divide by zero");

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.

Methods to print Exception Information:

a. e.printStackTrace(); : prints exception name, description and stacktrace.

b. Sout(e.toString); : prints exception name and description.

c. Sout(e.getMessage); : prints description.

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.

Eg. Class Test{

public static void main(String[] args){

try{

int a=100, b=0, c;

c = a/b;

sout(c);

catch(ArithemetiException e){

sout(e);

finally{

sout("I am in finally block");

}
• 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.

Finally block usage:

• 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.

// Java Program to demonstrates

// the working of finalize() Method

import java.util.*;

public class Geeks {

public static void main(String[] args)

Geeks g = new Geeks();

System.out.println("Hashcode is: " + g.hashCode());

// Making the object eligible for garbage collection

g = null;

System.gc();

// Adding a short delay to allow GC to act

try {
Thread.sleep(1000);

catch (InterruptedException e) {

e.printStackTrace();

System.out.println("End of the garbage collection");

// Defining the finalize method

@Override protected void finalize()

System.out.println("Called the finalize() method");

Combinations of try, catch and finally:

Link: https://medium.com/@rushilakade66/various-possible-combinations-of-try-catch-finally-
5e495667880e

throw keyword:

Eg. Class YoungerAgeException extends RuntimeException{

YoungerAgeException(String msg){

super(msg);

class voting{

public static void main(String[] args){

int age = 16;

if(age<18){

throw new YoungerAgeException("You are not eligible for voting");

else{sout("Vote Successfully");}
}

• Throw creates exception object manually(by programmer) and handover to JVM.

• We can throw either checked or unchecked exception but throw is best for customized
exception.

• We can only throw class that comes in throwable child class.

• 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.

Eg.. class ReadAndWrite{

void readFile() throws FileNotFoundException{

FileInputStream fis = new FileInputStream("d:/abc.txt");

class Test{

public static void main(String[] args){

ReadAndWrite rw = new ReadAndWrite();

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

1. throw keyword is used to 1. throws keyword is used to


create an exception object declare the exceptions i.e. it
manually i.e. by indicate the caller method that
programmer (otherwise by given type of exception can
default method is occur so you have to handle it
responsible to create while calling.
exception object).

2. throw keyword is mainly 2. throws keyword is mainly used


used for runtime exceptions for compile time exceptions or
or unchecked exceptions. checked exceptions.

3. In case of throw keyword 3. In case of throws keyword we


we can throw only single can declare multiple exceptions
exception. i.e. void readFile() throws
FileNotFoundException,
NullPointerException, etc.

4. throw keyword is used 4. throws keyword is used with


within the method. method signature.

5. throw keyword is followed 5. throws keyword is followed by


by new instance. class.

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:

1. Compiletime Custom Exception:

class UnderAgeException extends Exception{

UnderAgeException(){

super("you are under age");

class Voting{

public static void main(String[] args){

int age = 16;


try{

if(age<18){

throw new Exception UnderAgeException();

catch(UnderAgeException e){

e.printstackTrace();

2. Runtime Custom Exception:

class UnderAgeException extends RuntimeException{

UnderAgeException(){

super("you are under age");

class Voting{

public static void main(String[] args){

int age = 16;

if(age<18){

throw new Exception UnderAgeException(); //will be compiled but not handle exception

Note: What is a Non-Primitive Data Type?

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.

String class Syntax:

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 name = "xyz"; // this also creates an object.

There are three classes to create String- String, StringBuffer, StringBuilder.

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.

Why Strings are Immutable?

String city1 = "Delhi";

String city2 = "Delhi";

String city3 = "Delhi";

city1, city2, city3 all are referring to same object in SCP

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.

Why String is final class?

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.

Features of String class:

• 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.

• + Operator for Strings :- Multiple Strings can be concatinated using + operator.

• 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).

• Synchronization and Concurrency:- Making String immutable automatically makes them


thread safe thereby solving the synchronization issues.

• 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.

Difference Between == and equals():

• == operator is used for reference comparison (address comparison). It means == operator


checks if both reference variables point to same memory location or not.

• 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:

Some important String Constructors:

i. String(){ }

ii. public String(String s){ }

iii. public String(StringBuffer sb){ }

iv. public String(StringBuilder sb){ }


v. public String(char[] ch){ }

vi. public String(byte[] b){ } // let say byte[] b = {101,102,103}; it will convert to char like a,b,c

Why char array is preferred over String for storing passwords?

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

Sout(s1+10); output: Pen10 // but this whole is String it self

Sout(10+20+s1); output: 30Pen // as a String, it uses operator precedence

Sout(s1+10-5); // will give error as String can't be subtracted from integer

String class Methods:

Some important String Methods:

1. isEmpty() output: true or false

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.

2. length() output: number in integer

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.

3. trim() output: String value

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.

4. equals() output: true or false

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);

5. equalsIgnoreCase() output: true or false


This method is used to compare a specified String to another String, ignoring case considerations i.e.
lower case or upper case.

6. compareTo() output: number in integer

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);

7. compareToIgnoreCase() output: number in integer

The method compareToIgnoreCase() compares two strings just like compareTo() but it ignores case
i.e. it treats uppercase and lowercase letters as the same.

8. concat() output: String

This method concatenates one String to the end of another String.

9. join() output: String

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)

Eg. String.join(";","s1","s2"); CharSequence is an interface. In Java, interfaces can absolutely be


used as data types.

10. subSquence(int beginIndex, int endIndex) output: CharSequence

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);

11. substring(int beginIndex, int endIndex) output: String

substring(int beginIndex) output: String // from given index to last

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.

Eg. s.substring(3,9); , s.substring(0,0); output: nothing

12. replace() output: String

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.

Eg. Sting s1 = "this is demo";

sout(s1.replace("is","was")); output: thwas was demo

13. replaceFirst(String regex, String replacement) output: String USES REGULAR


EXPRESSION
This method replaces the first substring 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.

Eg: s1.replaceFirst("is","was"); output: thwas is demo

14. replaceAll(String regex, String replacement) output: String USES REGULAR


EXPRESSION

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.

Eg. s1.replaceAll("is",was"); output: thwas was demo

s1.replaceAll("is().",was"); output: thwaswasdemo // here we used regular expression.

15. indexOf(char c) output: integer number

indexOf(String s) output: integer number

This method returns the position of the first occurrence of specified character int a String or return -
1 if the character does not occur.

Eg. s.indexOf('d'); , s.indexOf("abc");

16. lastIndexOf() ouput: integer number

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.

17. charAt(int i) output: char

This method returns the charater at the specified index. But index value should lie between 0 and
length()-1.

Eg. s.charAt(3);

18. contains(String s) output: true or false

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");

19. startsWith(String s) output: true or false

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");

20. endsWith(String s) output: true or false

This method checks whether the String ends with a specified suffix. If yes , then method will return
true else flase. Eg. s.endsWith("d");

21. toUpperCase() output: String


This methods converts all characters of the String into a uppercase letter.

Eg. s.toUpperCase();

22. toLowerCase() output: String

This methods converts all characters of the String into a lowercase letter.

Eg. s.toLowerCase();

23. valueOf() output: String

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);

24. toCharArray() output: character array

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.

Eg. StringBuffer sb = new StringBuffer("xyz");

sb.append("abc"); this will change String to xyzabc without creating new object.

When we should use String and StringBuffer?

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.

Length: Number of characters currently present in the StringBuffer.

Capacity: Total number of characters it can hold before needing to grow.

StringBuffer class Syntax:

public final class StringBuffer extends AbstractStringBuilder implements java.i.o.Serializable,


CharSequence{ }

StringBuffer Constructors:

i. StringBuffer(){ } // with 16 default capacity

ii. StringBuffer(CharSequence seq){ }


iii. StringBuffer(String s){ }

iv. StringBuffer(int capacity){ } // used to provide default capacity

StringBuffer class Methods:

Some important StringBuffer Methods:

1. capacity() output: integer number

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();

2. append() output: StringBuffer

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.

Eg. sb.append("hello"); // now if we check its capacity it is still 16

sb.append("deepak javaa"); // now if we check its capacity it is 32

sb.append(" Text"); // String

sb.append(123); // int

sb.append(45.67); // double

sb.append(true); // boolean

sb.append('!'); // char

Everything gets converted to string and added at the end.

3. length() output: integer number

The length() method returns the number of characters currently stored in the StringBuffer.

Eg. sb.length();

4. charAt() output: char

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);

5. delete(int start, int end) output: stringBuffer

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);

6. deleteCharAt(int i) output: stringBuffer

Similar to delete() but removes the character at the specified index from the StringBuffer.

Eg. sb.deleteCharAt(4);

7. equals() output: true or false

StringBuffer inherits the equals() method from the Object class but

sb.equals() compares object references, not contents.

8. indexOf(String s) output: integer number

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");

9. lastIndexOf(String s) output: integer number

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.

10. insert(int index, datatype value) output: StringBuffer

The insert() method adds text or values at a specific position (index) inside a StringBuffer.

It shifts the existing characters to the right to make room.

Eg. sb.insert(index, value); You can insert:String, char, int, boolean, float, double, long, char[],
Object.

11. replace(int start, int end, String s) output: StringBuffer

The replace() method in StringBuffer replaces characters between the specified start and end indexes
with the provided new string.

Eg. sb.replace(3, 6, "m");

12. reverse() output: StringBuffer

The reverse() method reverses the characters in the StringBuffer and modifies the original buffer.

Eg. sb.reverse();

13. subSequence(int start, int end) output: CharSequence

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);

14. subString() output: String // and it similar to subString() in String

15. toString() output: String

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.

17. setCharAt(int index, char c) output: void

The setCharAt(int index, char c) method replaces the character at the specified index with the new
character c.

18. setLength(int l) output: void

The setLength() method sets the length of the StringBuffer.It either:

Truncates the content if newLength is less than the current length.

Expands the content and fills the extra characters with null characters (\u0000) if newLength is more
than the current length.

19. trimToSize() output: void

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.

To overcome the problem of slow performance of StringBuffer methods, Java introduced


StringBuilder concept and creates all the methods of StringBuilder as non-synchronized which
increases the methods performance.

StringBuilder class Syntax:

public final class StringBuilder extends AbstractStringBuilder implements java.i.o.Serializable,


CharSequence{ }

StringBuilder constructors same as StringBuffer constructors and methods also but methods are non-
syncrhonized.

D/B String, StringBuffer and StringBuilder:

String StringBuffer StringBuilder

1. String objects 1. StringBuffer 1. StringBuilder


are stored in objects are objects are
heap and stored in stored in heap
SCP. heap area. area.
2. String object 2. StrinBuffer 2. StrinBuffer
is immutable. object is object is
mutable. mutable.

3. If we change 3. If we change 3. If we change


the value of the value of the value of
String StringBuffer StringBuilder
Frequently , Frequently , it Frequently , it
it will take will consume will consume
more less memory. less memory.
memory.

4. String is not 4. StringBuffer is 4. StringBuilder


thread safe. thread safe. is not thread
safe.

5. Slow if data 5. Fast 5. Fast compared


changes compared to to StringBuffer.
frequently. String.

6. Use where 6. Use if data 6. Use if data


data not changes changes
changes frequently. frequently.
frequently.

Multithreading:

Thread: We can call it as Subtask or Subprocess etc.

Multitasking Multiprocessing Multithreading

• Performing • When one • Executing


multiple system is multiple
task at connected to threads at
single time multiple single time is
is known as processors in known as
Multitaskin order to Multithreadin
g. complete the g.
task is known
• Increases • Highly used in
as
the many software
Multiprocessin
performanc like VLC,
g.
e of CPU. Games etc.
• It is best
• It is best
suitable at
suitable at
• Can be system level or programming
achieved by OS level. level.
two types-

Process based Multitasking

Thread based Multitasking

Process Thread

1. A program which is in 1. It is subpart of process.


executing state is called
Process.

2. Process is heavy weight. 2. Thread is light weight.

3. Process takes more time for 3. Thread takes less time for
context switching. context switching.

4. Inter process communication 4. Inter thread communication


takes more time. takes less time.

5. Each process has different 5. Threads share same address


address space. space.

6. Processes are not dependent 6. Threads are not dependent


on each other. on each other.

7. Processes does not require 7. Threads may require


synchronization. synchronization.

8. Process takes more time in 8. Thread takes less time in


creation. creation.

9. Process require more time for 1. Thread require less time for
termination. termination.

How to create thread?

There are two ways to create thread-

Using Thread class and Using Runnable interface.

You might also like