This document provides an overview of object-oriented programming concepts in Java, including classes, objects, variables, methods, constructors, abstraction, encapsulation, inheritance, and polymorphism. It defines classes and objects, and describes how classes act as blueprints for objects. It explains the syntax for defining classes and class members like variables and methods. It also covers method overloading, different types of methods, and how constructors are used to initialize objects. The document concludes with brief explanations of abstraction, encapsulation, inheritance, and polymorphism as fundamental principles of object-oriented design.
Constructors initialize objects upon creation and are automatically called before the new operator completes. They look similar to methods but have no return type. This allows objects to initialize themselves when created. The this keyword can be used inside methods to refer to the current object. Static members can be accessed without creating an object and are used to define utility methods and variables. Arrays are implemented as objects in Java.
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
The lecture was condcuted by Tushar B Kute at YCMOU, Nashik through VLC orgnanized by MSBTE. The contents can be found in book "Core Java Programming - A Practical Approach' by Laxmi Publications.
This document discusses primitive data types, variables, classes, methods, constructors, and interfaces in Java. It provides details on the different primitive data types including their sizes and ranges. It describes how variables store values of a particular type. It outlines the syntax for class declarations including fields, methods, and constructors. It also covers method overloading, overriding, and parameter passing. Finally, it summarizes interfaces and how they define requirements for classes to implement.
This document provides an introduction to the Java programming language. It discusses the history and components of Java, including the Java language, platform, and tools. It then explains some key Java concepts like object-oriented programming, classes, objects, inheritance, and interfaces. It provides examples of how to write a simple Java program and declare methods. It also compares static and instance members and discusses abstract classes and when to use interfaces versus abstract classes.
This document provides an overview of object-oriented programming concepts in Java including two programming paradigms, OOP principles like encapsulation, polymorphism, abstraction and inheritance. It discusses classes, objects, and reference variables in Java. Key points covered are how classes act as blueprints for objects, the difference between objects and reference variables, and how methods can be called on objects.
Class is a blueprint for creating objects that share common attributes and behaviors. A class defines the data and methods that describe the object. Classes in Java can contain data members, methods, constructors, nested classes, and interfaces. Objects are instances of classes that occupy memory at runtime and can access class members like variables and methods. Constructors initialize an object when it is created and have the same name as the class. The this keyword refers to the current object in a method or constructor. Command line arguments can be passed to a program as strings and accessed via the args parameter in the main method.
Class is a blueprint that defines the properties and behaviors that objects of that class will have. It represents the state and behavior of specific objects. Constructors are special methods used to initialize objects, and are called when an object is created. Methods define the behaviors of objects and can be user-defined or predefined. The garbage collector automatically reclaims unused memory by destroying unused objects.
This document discusses classes, methods, objects, constructors and other object-oriented programming concepts in Java. Some key points:
- Classes are templates that define objects, while objects are instances of classes that have state and behavior.
- Methods are collections of code that perform specific tasks and provide reusability. The main() method is important as it is executed first.
- Constructors initialize objects and are automatically called when objects are created. There can be default and parameterized constructors.
- Objects are created using the new keyword and access class members like methods using the dot operator. Arrays can store multiple objects.
- Methods and constructors can be overloaded when they have the same name but different parameters
1. A class is a blueprint for objects that defines common properties and methods. It can include modifiers, name, superclass/interfaces, and a class body.
2. An object is created using the new keyword, assigning the object to a reference variable. Reference variables store an object's address in memory. Assigning one reference variable to another does not create distinct copies but points to the same object.
3. A method performs a specific task and can return a result. It includes modifiers, return type, name, parameters, and a method body. Method overloading allows methods with the same name but different parameters.
The document discusses key concepts in Object Oriented Programming (OOP) in Java including classes, objects, references, constructors, inheritance, abstraction, polymorphism, and generics. It defines classes as blueprints for objects, and objects as instances of classes that have state and behavior. Constructors are used to initialize new objects. Inheritance and abstraction allow classes to extend and implement other classes and interfaces. Polymorphism enables different classes to implement the same methods in different ways. Generics provide type safety for collections of objects.
The document discusses classes and methods in Java. It defines classes as containing data declarations (instance variables) and method declarations. Methods group statements to perform well-defined tasks. Method declarations specify the name, return type, and parameters. The method body contains the statements. Methods can call other methods and control program flow. Overloading allows multiple methods with the same name but different parameters. Variables have either class or block scope depending on where they are declared. Parameters are passed by value for primitives and by reference for objects. The document provides an example Month class to demonstrate these concepts.
Class is a blueprint for creating object instances that share common attributes and behaviors. It defines the variables and methods that are common to all objects of that class. When an object is created from a class, it is said to be an instance of that class. Objects contain state in the form of attributes and behavior in the form of methods. Classes in Java can define access levels for variables and methods as public, private, protected, or without a specified level (default).
JVM is the abstract machine that executes Java bytecode. JRE provides the runtime environment and implements the JVM. JDK includes JRE plus development tools.
The JVM loads class bytecode into memory areas like the method area and heap. Each thread gets its own stack for method calls.
Core OOP concepts in Java include encapsulation, inheritance, polymorphism, and abstraction. Access modifiers control visibility. Methods can be overloaded or overridden. Classes and variables can be marked as final, abstract, or static.
Java supports primitive types and reference types. Reference variables point to objects in memory rather than containing values. Primitive types are passed by value while references are passed by reference.
Vbnnmhvbbnnnfcfcgvsbsbnssbbsbsnsbbssbbsbsbssbbsbsbsbsbsbsbdbsbsbsbbbbnnhjzjshdhshsshhsbdbxbxbxxbbcnxnxncncncncncnccnbbbhahhehehehenendhdhdhdbfnffnñnfjdjejejhegegehebebehehehehehehehebeebhehejdjdejjrejrjekjdndbdbddbbdnrbnnnnsnsnhshsil feb cagoudgjvzcczhfHafhsfjgsjgjsjfszfbfbzfsbfzbfzbcbzxbczbzfbzvczgjjscfsjgdjhzdgjjgsvnzgjzzgjjzgzvnzgjv
This document discusses objects and classes in Java. It defines a class as defining the properties and behaviors of objects. An object represents a real-world entity with a unique identity, state, and behavior. The document discusses declaring objects using the new keyword, defining and calling methods in classes, arrays of objects, constructors, the this keyword, and static members. It provides examples of defining classes, declaring objects, defining methods with and without return values, and passing objects as parameters.
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
The document discusses various object-oriented programming concepts in Java including classes, objects, constructors, method overloading, passing arguments, returning objects, recursion, the 'new' operator, 'this' and 'static' keywords, and inner classes. It provides examples to illustrate class and object declarations, creating objects using the new operator, using constructors, overloading methods and constructors, passing arguments by value and reference, returning objects from methods, using recursion to calculate factorials, and using the this and static keywords.
Static members in Java include static variables, static blocks, and static methods.
Static variables and blocks are initialized when the class is loaded, while static methods can be accessed without creating an object. Overloading static methods is allowed by having multiple methods with the same name but different parameters. The order of execution is that static variables and blocks are initialized in the order they are declared, followed by the main method.
The document discusses basic Java concepts including identifiers, keywords, literals, primitive data types, variables, operators, control flow statements, classes, methods, inheritance, polymorphism, packages and modifiers. It provides definitions and examples of key concepts like classes, objects, methods, inheritance, polymorphism, packages, modifiers, variables and data types. It also lists Java keywords, reserved words and literals.
This document discusses object-oriented programming concepts in Kotlin such as classes, objects, methods, and static methods. It provides examples of defining classes that represent real-world entities like cars. Objects are defined as instances of classes that contain an address and occupy memory. Methods are functions that are part of a class and can be invoked by objects. Static methods belong to a class rather than individual objects.
The document provides examples of various Java programming concepts like displaying messages, using control structures like if-else, for loops, methods, constructors, access specifiers, static variables and more. It shows how to write simple Java programs to print messages, integers, use conditional and looping statements. It also explains concepts like default and parameterized constructors, static and non-static methods, different access specifiers and their usage. The examples help learn how different Java features can be used to develop programs with classes, objects and methods.
Class is a blueprint for creating objects that share common attributes and behaviors. A class defines the data and methods that describe the object. Classes in Java can contain data members, methods, constructors, nested classes, and interfaces. Objects are instances of classes that occupy memory at runtime and can access class members like variables and methods. Constructors initialize an object when it is created and have the same name as the class. The this keyword refers to the current object in a method or constructor. Command line arguments can be passed to a program as strings and accessed via the args parameter in the main method.
Class is a blueprint that defines the properties and behaviors that objects of that class will have. It represents the state and behavior of specific objects. Constructors are special methods used to initialize objects, and are called when an object is created. Methods define the behaviors of objects and can be user-defined or predefined. The garbage collector automatically reclaims unused memory by destroying unused objects.
This document discusses classes, methods, objects, constructors and other object-oriented programming concepts in Java. Some key points:
- Classes are templates that define objects, while objects are instances of classes that have state and behavior.
- Methods are collections of code that perform specific tasks and provide reusability. The main() method is important as it is executed first.
- Constructors initialize objects and are automatically called when objects are created. There can be default and parameterized constructors.
- Objects are created using the new keyword and access class members like methods using the dot operator. Arrays can store multiple objects.
- Methods and constructors can be overloaded when they have the same name but different parameters
1. A class is a blueprint for objects that defines common properties and methods. It can include modifiers, name, superclass/interfaces, and a class body.
2. An object is created using the new keyword, assigning the object to a reference variable. Reference variables store an object's address in memory. Assigning one reference variable to another does not create distinct copies but points to the same object.
3. A method performs a specific task and can return a result. It includes modifiers, return type, name, parameters, and a method body. Method overloading allows methods with the same name but different parameters.
The document discusses key concepts in Object Oriented Programming (OOP) in Java including classes, objects, references, constructors, inheritance, abstraction, polymorphism, and generics. It defines classes as blueprints for objects, and objects as instances of classes that have state and behavior. Constructors are used to initialize new objects. Inheritance and abstraction allow classes to extend and implement other classes and interfaces. Polymorphism enables different classes to implement the same methods in different ways. Generics provide type safety for collections of objects.
The document discusses classes and methods in Java. It defines classes as containing data declarations (instance variables) and method declarations. Methods group statements to perform well-defined tasks. Method declarations specify the name, return type, and parameters. The method body contains the statements. Methods can call other methods and control program flow. Overloading allows multiple methods with the same name but different parameters. Variables have either class or block scope depending on where they are declared. Parameters are passed by value for primitives and by reference for objects. The document provides an example Month class to demonstrate these concepts.
Class is a blueprint for creating object instances that share common attributes and behaviors. It defines the variables and methods that are common to all objects of that class. When an object is created from a class, it is said to be an instance of that class. Objects contain state in the form of attributes and behavior in the form of methods. Classes in Java can define access levels for variables and methods as public, private, protected, or without a specified level (default).
JVM is the abstract machine that executes Java bytecode. JRE provides the runtime environment and implements the JVM. JDK includes JRE plus development tools.
The JVM loads class bytecode into memory areas like the method area and heap. Each thread gets its own stack for method calls.
Core OOP concepts in Java include encapsulation, inheritance, polymorphism, and abstraction. Access modifiers control visibility. Methods can be overloaded or overridden. Classes and variables can be marked as final, abstract, or static.
Java supports primitive types and reference types. Reference variables point to objects in memory rather than containing values. Primitive types are passed by value while references are passed by reference.
Vbnnmhvbbnnnfcfcgvsbsbnssbbsbsnsbbssbbsbsbssbbsbsbsbsbsbsbdbsbsbsbbbbnnhjzjshdhshsshhsbdbxbxbxxbbcnxnxncncncncncnccnbbbhahhehehehenendhdhdhdbfnffnñnfjdjejejhegegehebebehehehehehehehebeebhehejdjdejjrejrjekjdndbdbddbbdnrbnnnnsnsnhshsil feb cagoudgjvzcczhfHafhsfjgsjgjsjfszfbfbzfsbfzbfzbcbzxbczbzfbzvczgjjscfsjgdjhzdgjjgsvnzgjzzgjjzgzvnzgjv
This document discusses objects and classes in Java. It defines a class as defining the properties and behaviors of objects. An object represents a real-world entity with a unique identity, state, and behavior. The document discusses declaring objects using the new keyword, defining and calling methods in classes, arrays of objects, constructors, the this keyword, and static members. It provides examples of defining classes, declaring objects, defining methods with and without return values, and passing objects as parameters.
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
The document discusses various object-oriented programming concepts in Java including classes, objects, constructors, method overloading, passing arguments, returning objects, recursion, the 'new' operator, 'this' and 'static' keywords, and inner classes. It provides examples to illustrate class and object declarations, creating objects using the new operator, using constructors, overloading methods and constructors, passing arguments by value and reference, returning objects from methods, using recursion to calculate factorials, and using the this and static keywords.
Static members in Java include static variables, static blocks, and static methods.
Static variables and blocks are initialized when the class is loaded, while static methods can be accessed without creating an object. Overloading static methods is allowed by having multiple methods with the same name but different parameters. The order of execution is that static variables and blocks are initialized in the order they are declared, followed by the main method.
The document discusses basic Java concepts including identifiers, keywords, literals, primitive data types, variables, operators, control flow statements, classes, methods, inheritance, polymorphism, packages and modifiers. It provides definitions and examples of key concepts like classes, objects, methods, inheritance, polymorphism, packages, modifiers, variables and data types. It also lists Java keywords, reserved words and literals.
This document discusses object-oriented programming concepts in Kotlin such as classes, objects, methods, and static methods. It provides examples of defining classes that represent real-world entities like cars. Objects are defined as instances of classes that contain an address and occupy memory. Methods are functions that are part of a class and can be invoked by objects. Static methods belong to a class rather than individual objects.
The document provides examples of various Java programming concepts like displaying messages, using control structures like if-else, for loops, methods, constructors, access specifiers, static variables and more. It shows how to write simple Java programs to print messages, integers, use conditional and looping statements. It also explains concepts like default and parameterized constructors, static and non-static methods, different access specifiers and their usage. The examples help learn how different Java features can be used to develop programs with classes, objects and methods.
11th International Conference on Data Mining (DaMi 2025)kjim477n
Welcome To DAMI 2025
Submit Your Research Articles...!!!
11th International Conference on Data Mining (DaMi 2025)
July 26 ~ 27, 2025, London, United Kingdom
Submission Deadline : June 07, 2025
Paper Submission : https://csit2025.org/submission/index.php
Contact Us : Here's where you can reach us : [email protected] or [email protected]
For more details visit : Webpage : https://csit2025.org/dami/index
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyYannis
The doctoral thesis trajectory has been often characterized as a “long and windy road” or a journey to “Ithaka”, suggesting the promises and challenges of this journey of initiation to research. The doctoral candidates need to complete such journey (i) preserving and even enhancing their wellbeing, (ii) overcoming the many challenges through resilience, while keeping (iii) high standards of ethics and (iv) scientific rigor. This talk will provide a personal account of lessons learnt and recommendations from a senior researcher over his 30+ years of doctoral supervision and care for doctoral students. Specific attention will be paid on the special features of the (i) interdisciplinary doctoral research that involves Information and Communications Technologies (ICT) and other scientific traditions, and (ii) the challenges faced in the complex technological and research landscape dominated by Artificial Intelligence.
A SEW-EURODRIVE brake repair kit is needed for maintenance and repair of specific SEW-EURODRIVE brake models, like the BE series. It includes all necessary parts for preventative maintenance and repairs. This ensures proper brake functionality and extends the lifespan of the brake system
Rearchitecturing a 9-year-old legacy Laravel application.pdfTakumi Amitani
An initiative to re-architect a Laravel legacy application that had been running for 9 years using the following approaches, with the goal of improving the system’s modifiability:
・Event Storming
・Use Case Driven Object Modeling
・Domain Driven Design
・Modular Monolith
・Clean Architecture
This slide was used in PHPxTKY June 2025.
https://phpxtky.connpass.com/event/352685/
A substation at an airport is a vital infrastructure component that ensures reliable and efficient power distribution for all airport operations. It acts as a crucial link, converting high-voltage electricity from the main grid to the lower voltages needed for various airport facilities. This essay will explore the functions, components, and importance of a substation at an airport.
Functions of an Airport Substation:
Voltage Conversion:
Substations step down high-voltage electricity to lower levels suitable for airport operations, like terminal buildings, runways, and other facilities.
Power Distribution:
They distribute electricity to various loads, including lighting, air conditioning, navigation systems, and ground support equipment.
Grid Stability:
Substations help maintain the stability of the power grid by controlling voltage levels and managing power flows.
Redundancy and Reliability:
Airports often have redundant substations or interconnected systems to ensure uninterrupted power supply, even in case of a fault.
Switching and Control:
Substations provide switching capabilities to connect or disconnect circuits, enabling maintenance and power management.
Protection:
Substations incorporate protective devices, like circuit breakers and relays, to safeguard the power system from faults and ensure safe operation.
Key Components of an Airport Substation:
Transformers: These convert high-voltage electricity to lower voltage levels.
Circuit Breakers: These devices switch circuits on or off, protecting the system from faults.
Busbars: These are large, conductive bars that distribute electricity from transformers to other equipment.
Switchgear: This includes equipment that controls the flow of electricity, such as isolators and switches.
Control and Protection Systems: These systems monitor the substation's performance, detect faults, and automatically initiate corrective actions.
Capacitors: These improve the power factor and reduce losses in the system.
Importance of Airport Substations:
Reliable Power Supply:
Substations are essential for providing reliable power to critical airport functions, ensuring safety and efficiency.
Safe and Efficient Operations:
They contribute to the safe and efficient operation of runways, terminals, and other airport facilities.
Airport Infrastructure:
Substations are an integral part of the airport's infrastructure, enabling various operations and services.
Economic Impact:
Substations support the economic activities of the airport, including passenger and cargo handling.
Modernization and Sustainability:
Modern substations incorporate advanced technologies and systems to improve efficiency, reduce energy consumption, and enhance sustainability.
In conclusion, an airport substation is a crucial component of airport infrastructure, ensuring reliable and efficient power distribution, grid stability, and safe operations.
2. Class & Object
• Everything in Java is associated with classes and objects, along with its
attributes and methods.
• For example: in real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
• It is a user-defined blueprint or prototype from which objects are created. E.g.
Student is a class while a particular student named Ravi is an object.
• A Class in Java may contain:
• Data member, Method, Constructor, Nested Class, Interface
• Objects are the instances of a class that are created to use the attributes and
methods of a class.
• When an object of a class is created, the class is said to be instantiated.
3. Example
class Student {
int id;
String name;
public static void main(String args[])
{
Student s1; //Declaration
s1 = new Student(); //Instantiate
System.out.println(s1.id);
System.out.println(s1.name);
}
}
null
s1
s1
Student
Object
4. • Create multiple objects:
Student S1=new Student();
Student S2=new Student();
…. So on
• It is possible to create multiple objects share the same reference.
Student S1=new Student();
Student S2=S1; Student
Object
S1
S2
5. Access Modifier
• Access modifiers help to restrict the scope of a class, constructor,
variable, method, or data member.
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
default The code is only accessible in the same package. This is used when you don't specify a
modifier.
protected The code is accessible in the same package and subclasses.
7. class Book {
String title;
String author;
public void setTitle(String bookTitle) {
title = bookTitle;
}
public void setAuthor(String bookAuthor) {
author = bookAuthor;
}
public void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
}
}
public class BookDemo {
public static void main(String[] args) {
Book book1 = new Book();
Book book2 = new Book();
book1.setTitle(“Java: The Complete Reference");
book1.setAuthor("Herbert Schildt");
book2.setTitle("Head First Java");
book2.setAuthor("Kathy Sierra");
System.out.println("Details of book1:");
book1.displayDetails();
System.out.println("nDetails of book2:");
book2.displayDetails();
}
}
8. Method overloading
• Method overloading allows a class to have more than one method with
the same name, but different parameter lists (i.e., different number or
types of parameters).
• It is Compile-time Polymorphism, Static Polymorphism, or Early binding.
• Different Ways of Method Overloading in Java
• Changing the Number of Parameters.
• Changing Data Types of the Arguments.
• Changing the Order of the Parameters of Methods
• Key Rules:
• Same method name
• Methods must differ in the number or types of parameters (method signature).
• The return type can be different but is not considered part of the method signature
for overloading.
• Method overloading can’t be done by changing the return type alone.
9. Example
class Calculator {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public double add(int a, double b) {
return a + b;
}
}
public class MethodOverloadingDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
// Calling the different overloaded add methods
System.out.println("Sum of two integers: " +
calc.add(10, 20)); // Calls add(int, int)
System.out.println("Sum of three integers: " +
calc.add(10, 20, 30)); // Calls add(int, int, int)
System.out.println("Sum of two doubles: " +
calc.add(5.5, 7.3)); // Calls add(double, double)
System.out.println("Sum of an int and a double: " +
calc.add(10, 7.8)); // Calls add(int, double)
}
}
10. What if the exact prototype does not match with
arguments?
• Priority-wise, the compiler takes these
steps:
• Type Conversion but to a higher type(in
terms of range) in the same family.
• Type conversion to the next higher
family(suppose if there is no long data type
available for an int data type, then it will
search for the float data type).
11. Example
class Demo {
public void show(int x) {
System.out.println("In int" + x);
}
public void show(String s) {
System.out.println("In String" + s);
}
public void show(byte b) {
System.out.println("In byte" + b);
}
}
class UseDemo {
public static void main(String[] args)
{
byte a = 25;
Demo obj = new Demo();
obj.show(a);
obj.show("hello");
obj.show(250);
obj.show('A');
obj.show("A");
obj.show(7.5);
}
}
12. Static method
• Any method that uses the static keyword is referred to as a static method.
• A static method in Java is a method that is part of a class rather than an
instance of that class.
• Every instance of a class has access to the method.
• Static methods have access to class variables (static variables) without using
the class’s object (instance).
• Only static data may be accessed by a static method. It is unable to access data
that is not static (instance variables).
Access_modifier static void methodName()
{
} // Method body.
Syntax to call a static method: className.methodName();
13. The static method does not have access to the instance variable
import java.io.*;
public class Test {
static int a = 40;
int b = 50;
void simpleDisplay()
{
System.out.println(a);
System.out.println(b);
}
static void staticDisplay()
{
System.out.println(a);
}
public static void main(String[] args)
{
GFG obj = new GFG();
obj.simpleDisplay();staticDisplay();
}
}
14. In both static and non-static methods, static methods are
directly accessed.
import java.io.*;
public class StaticExample {
static int num = 100;
static String str = "GeeksForGeeks";
static void display()
{
System.out.println("static number is " + num);
System.out.println("static string is " + str);
}
void nonstatic()
{
display();
}
public static void main(String args[])
{
StaticExample obj = new StaticExample();
obj.nonstatic();
display();
}
}
15. • Why use Static Methods?
• To access and change static variables and other non-object-based static
methods.
• Utility and assist classes frequently employ static methods.
• Restrictions in Static Methods:
• Non-static data members or non-static methods cannot be used by static
methods, and static methods cannot call non-static methods directly.
• In a static environment, this and super aren’t allowed to be used.
• Why is the main method in Java static?
• It’s because calling a static method isn’t needed of the object. If it were a non-
static method, JVM would first build an object before calling the main()
method, resulting in an extra memory allocation difficulty.
16. Difference Between the static method and instance method
Instance Methods Static Methods
It requires an object of the class. It doesn’t require an object of the class.
It can access all attributes of a class. It can access only the static attribute of a class.
The methods can be accessed only using object
reference.
The method is only accessed by class name.
Syntax: Objref.methodname() Syntax: className.methodname()
It’s an example of pass-by-value programming.
It is an example of pass-by-reference
programming.
17. ‘this’ keyword
• In Java, the this keyword is a special reference variable used within an
instance method or constructor to refer to the current object.
• It helps to distinguish between instance variables and parameters or local
variables with the same name
• Key Uses of this Keyword
• Refer to Instance Variables: When local variables or parameters have the same
name as instance variables, this is used to refer to the instance variables.
• Invoke Other Constructors: this can be used to call another constructor in the same
class (constructor chaining).
• Pass the Current Object: this can be passed as an argument to methods or
constructors of other classes.
• Return the Current Object: this can be used to return the current object from a
method, often used in method chaining.
18. Example
class Person {
String name;
int age;
public void setDetails(String name, int age) {
this.name = name; // Refers to the instance variable 'name'
this.age = age; // Refers to the instance variable 'age'
}
public void displayInfo() {
System.out.println("Name: " + this.name + ", Age: " + this.age);
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person();
person.setDetails("Alice", 30);
person.displayInfo(); // Output: Name: Alice, Age: 30
}
}
19. Java Memory Structure
• The major concepts in Java Memory
Management :
• JVM Memory Structure
• Garbage Collector
• Java Memory Structure:
• Some of the areas are created by the JVM
whereas some are created by the threads
that are used in a program.
• memory area created by JVM is destroyed
only when the JVM exits.
• The data areas of thread are created
during instantiation and destroyed when
the thread exits.
20. • Heap :
• stores the actual object in a memory.
• Heap can be of fixed or dynamic size depending upon the system’s
configuration.
• The user can control the heap.
• When a new keyword is used, object is assigned a space in heap,
but the reference of the same exists onto the stack.
• Scanner sc = new Scanner(System.in);
• The above statement creates the object of Scanner class which
gets allocated to heap whereas the reference ‘sc’ gets pushed to
the stack.
• Note: Garbage collection in heap area is mandatory.
21. • Method Area (Metaspace):
• It is a logical part of the heap area and is created on virtual
machine startup.
• This memory is allocated for the following:
• Bytecode: The compiled bytecode from .class files.
• Class Metadata: Information about class methods, fields, and constants.
• Static Variables: Static variables are also stored here.
• Can be of a fixed size or expanded as required by the computation.
• Needs not to be contiguous.
22. • JVM Stacks:
• A stack is created at the same time when a thread is created and is used to
store data and partial results which will be needed while returning value for
method and performing dynamic linking.
• Stacks can either be of fixed or dynamic size.
• The memory for stack needs not to be contiguous.
• Native method Stacks:
• It is used for native code written in non-Java languages such as C or C++.
When Java invokes native methods, their execution is managed in this stack,
rather than the Java stack.
23. • Program counter (PC) registers:
• Each thread has its own PC register, which keeps track of the current
execution point within the thread. It stores the memory address of
the instruction currently being executed.
24. Memory Allocation Process:
Method Area (Metaspace): The static variable x
and the class-level information of Example are
stored in the Metaspace.
Heap: The object obj is created on the heap, and
its instance variable y is stored here as well.
Stack: The reference to the object obj and the
local variable localVariable in the
instanceMethod are stored in the stack.
class Example {
static int x = 10; // Stored in Method Area (Metaspace)
int y; // Instance variable, stored in Heap
public Example(int y) {
this.y = y;
}
public static void staticMethod() {
System.out.println("Static method called");
}
public void instanceMethod() {
int localVariable = 20; // Local variable, stored in Stack
System.out.println("Instance method called: " + y + ", " + localVariable);
}
public static void main(String[] args) {
Example obj = new Example(30); / / obj stored in Heap, reference stored in Stack
obj.instanceMethod(); // Method execution creates a stack frame with local variables
Example.staticMethod(); // Static method executed without instance
}
}
25. Garbage collection
• In Java, memory management is primarily handled through automatic garbage collection,
which means that the developer doesn’t need to explicitly manage memory allocation and
deallocation.
• The garbage collector (GC) is a part of the Java JVM (Java Virtual Machine) responsible for
automatically reclaiming memory that is no longer in use by the program, i.e., memory
occupied by objects that are no longer reachable by any active part of the application.
• Garbage collection techniques include:
• Minor GC: Focuses on the Young Generation.
• The young generation is where new objects are allocated.
• Major GC: Focuses on the Old Generation.
• If an object survives several garbage collection cycles, it is promoted to the Old Generation.
• This region holds objects that have survived several garbage collection cycles in the young generation
and are considered long-lived.
Note: System.gc() and Runtime.gc() are the methods which requests for Garbage collection to JVM
explicitly but it doesn’t ensures garbage collection as the final decision of garbage collection is of JVM only.
26. Constructor
• A constructor in Java is a special method that is used to initialize
objects.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• The constructor(s) of a class must have the same name as the class
name in which it resides.
• Access modifiers can be used in constructor declaration to control its
access i.e which other class can call the constructor.
27. class Person {
String name;
int age;
Public void setData(String name, int age) {
this.name = name;
this.age = age;
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person(); person1.setData("Alice", 25);
Person person2 = new Person(); person2.setData ("Bob", 30);
person1.displayInfo(); // Output: Name: Alice, Age: 25
person2.displayInfo(); // Output: Name: Bob, Age: 30
}
}
28. Types of Constructors in Java
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• Default Constructor
• A constructor that has no parameters is known as default the constructor.
• The default constructor can be implicit or explicit.
• If we don’t define explicitly, we get an implicit default constructor. If we
manually write a constructor, the implicit one is overridded.
• Note: Default constructor provides the default values to the object like 0, null,
etc. depending on the type.
29. Default
constructor
class Car {
String model;
int year;
public Car() {
model = "Unknown";
year = 2000;
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.displayInfo(); // Output: Car Model: Unknown, Year: 2000
}
}
30. Parametrized
constructor
• A constructor that has
parameters is known as
parameterized constructor.
• If we want to initialize fields
of the class with our own
values, then use a
parameterized constructor.
• Constructors do not return
values.
class Car {
String model;
int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public void displayInfo() {
System.out.println("Car Model: " + model + ", Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2021);
myCar.displayInfo(); // Output: Car Model: Toyota, Year: 2021
}
}
31. Constructor overloading
• Just like methods, we can overload constructors for creating objects
in different ways.
• The compiler differentiates constructors on the basis of the number
of parameters, types of parameters, and order of the parameters.
• Constructor overloading allows you to create objects in different ways
(with different sets of initial values), making it more flexible and
easier to handle different situations during object instantiation.
• When there is no exact match for the constructor parameters
provided during object creation, the Java compiler will try to promote
smaller data types to a larger compatible type, similar to method
overloading.
32. import java.io.*;
class Geek {
Geek(String name) {
System.out.println("Constructor with one " + "argument - String : " + name); }
Geek(String name, int age){
System.out.println( "Constructor with two arguments : " + " String and Integer : " + name + " " + age); }
Geek(long id) {
System.out.println("Constructor with one argument : "+ "Long : " + id); }
}
class Test {
public static void main(String[] args) {
Geek geek2 = new Geek("Shikhar");
Geek geek3 = new Geek("Dharmesh", 26);
Geek geek4 = new Geek(325614567);
}
}
33. Call of one constrictor to another constructor
• In Java, one constructor can be called from another constructor in the
same class using the ‘this’ keyword. This is known as constructor
chaining.
• It allows the reuse of constructor code.
class Temp{
Temp(){
this(5); // calls constructor 2
System.out.println("The Default constructor");
}
Temp(int x){ //constructor 2
this(5, 15); // calls constructor 3
System.out.println(x);
}
Temp(int x, int y){ //constructor 3
System.out.println(x * y);
}
public static void main(String args[])
{
// invokes default constructor first
new Temp();
}
}
34. Copy Constructor
• A copy constructor in Java is a special type of constructor used to create a
new object as a copy of an existing object.
• This concept is borrowed from C++ and is not built into Java like other
languages, but it can be implemented manually.
• we can create our own copy constructor by passing the object of the same
class to the other instance(object) of the class.
• Purpose of a Copy Constructor
• Create a Duplicate: It allows you to create a new object that is a copy of an existing
object, including its state (i.e., the values of its attributes).
• Deep Copy: In cases where an object contains references to other objects, a copy
constructor can be used to perform a deep copy, ensuring that the new object and
the original object do not share references to mutable objects.
35. Copy Constructor
class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(Person other) {
this.name = other.name; // Copy the name
this.age = other.age; // Copy the age
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " +
age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 30);
Person person2 = new Person(person1);
System.out.println("Original Person:");
person1.displayInfo();
System.out.println();
System.out.println("Copied Person:");
person2.displayInfo();
}
}
36. Wrapper class
• In Java, wrapper classes are used to convert primitive data types (like
int, char, etc.) into objects.
• What we need Wrapper class?
• They convert primitive data types into objects. Objects are needed if we wish
to modify the arguments passed into a method (because primitive types are
passed by value).
• This allows primitive values to be treated as objects, which is necessary when
working with collections (like ArrayList and Vector)
• The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
• An object is needed to support synchronization in multithreading.
37. Primitive Data Types and their Corresponding Wrapper Class
Primitive Data Type Wrapper Class
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
38. Features of Wrapper class
1. Java automatically converts between primitive types and their
corresponding wrapper objects.
• Autoboxing
• The automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing. For example –
conversion of int to Integer, long to Long, double to Double, etc.
int x = 10;
Integer obj = x; // Autoboxing: int to Integer
• Unboxing
• Converting a wrapper object back into its corresponding primitive type.
Integer obj = 20;
int y = obj; // Unboxing: Integer to int
39. Features of Wrapper class
1. Useful Methods:Wrapper classes provide various methods to
manipulate and convert data. For example:
• Integer.parseInt("123"): Converts a string to an int.
• Double.toString(10.5): Converts a double to a String.
2. Immutable Objects:
Wrapper objects are immutable, meaning their values cannot be
changed after they are created.
3. Usage in Collections:Since collections like ArrayList, HashMap, etc.,
only work with objects, wrapper classes allow the use of primitive
values in these structures.
• ArrayList<Integer> list = new ArrayList<>();
• list.add(10); // Autoboxing: int to Integer
40. Example
public class WrapperExample {
public static void main(String[] args) {
int num = 100;
Integer obj = num; // Autoboxing: primitive to object
int value = obj; // Unboxing: object to primitive
String str = Integer.toString(num);
int parsedValue = Integer.parseInt("123");
System.out.println("Object value: " + obj);
System.out.println("Primitive value: " + value);
System.out.println("Parsed value: " + parsedValue);
}
}
41. Example
import java.util.ArrayList;
import java.util.HashMap;
public class WrapperClassInCollections {
public static void main(String[] args) {
ArrayList<Integer> integerList = new ArrayList<>();
integerList.add(10); // autoboxed to Integer
integerList.add(20);
integerList.add(30);
System.out.println("ArrayList contents:");
for (Integer num : integerList) {
System.out.println(num);
}
HashMap<String, Double> priceMap = new HashMap<>();
// Adding key-value pairs (autoboxing will occur for Double)
priceMap.put("Apple", 1.99);
priceMap.put("Banana", 0.59);
priceMap.put("Cherry", 2.99);
// Accessing and printing values
System.out.println("nHashMap contents:");
for (String key : priceMap.keySet()) {
Double price = priceMap.get(key); // unboxing occurs here
System.out.println(key + ": $" + price);
}
}
}
42. import java.io.*;
class GFG {
public static void main(String[] args){
byte a = 1;
Byte byteobj = new Byte(a);
int b = 10;
Integer intobj = new Integer(b);
float c = 18.6f;
Float floatobj = new Float(c);
double d = 250.5;
Double doubleobj = new Double(d);
char e = 'a';
Character charobj = e;
System.out.println( "Values of Wrapper objects (printing as objects)");
System.out.println("nByte object byteobj: "+ byteobj);
System.out.println("nInteger object intobj: "+ intobj);
System.out.println("nFloat object floatobj: " + floatobj);
System.out.println("nDouble object doubleobj: "+ doubleobj);
System.out.println("nCharacter object charobj: "+ charobj);
// objects to data types (retrieving data types from objects)
unwrapping objects to primitive data types
byte bv = byteobj;
int iv = intobj;
float fv = floatobj;
double dv = doubleobj;
char cv = charobj;
System.out.println("nUnwrapped values (printing as data
types)");
System.out.println("nbyte value, bv: " + bv);
System.out.println("nint value, iv: " + iv);
System.out.println("nfloat value, fv: " + fv);
System.out.println("ndouble value, dv: " + dv);
System.out.println("nchar value, cv: " + cv);
}
}
43. Array
• Arrays are fundamental structures in Java that allow us to store multiple values of the same type in a single variable.
• Arrays in Java work differently than they do in C/C++. Arrays are objects in Java.
• In Java, all arrays are dynamically allocated.
• An array can contain primitives (int, char, etc.) and object (or non-primitive) references of a class, depending on the
definition of the array. In the case of primitive data types, the actual values might be stored in contiguous memory
locations (JVM does not guarantee this behavior). In the case of class objects, the actual objects are stored in a heap
segment.
• Array Declaration
• // Declaration without size (size will be specified later)
• int[] myArray; // or int myArray[];
• // Declaration and creation of an array with size 5
• int[] myArray = new int[5];
• Initializing an Array
• // Initializing while declaring
• int[] myArray = {10, 20, 30, 40, 50};
• // Creating an array and then assigning values
• int[] myArray = new int[5]; // Array of size 5 with default values (0)
• myArray[0] = 10; // Assigning values to elements
• myArray[1] = 20;
• Array Length
• int length = myArray.length;
44. Example of Array Declaration, Initialization, and Usage:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5}; // Declare and initialize an array of integers
System.out.println("First element: " + numbers[0]); // Output: 1
System.out.println("Third element: " + numbers[2]); // Output: 3
// Modifying an element
numbers[1] = 20; // Change the second element
System.out.println("Modified array: ");
// Looping through the array and printing all elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
45. Types of Array
• Single Dimensional Array
• Multidimensional Array
• Note: JVM throws ArrayIndexOutOfBoundsException to indicate that
the array has been accessed with an illegal index.
46. Single Dimension Array
• These are the most common type of arrays, where elements are
stored in a linear order.
• int[] singleDimArray = {1, 2, 3, 4, 5}; // A single-dimensional array
47. Multi-Dimensional Arrays
• In Java, multi-dimensional arrays are arrays of arrays.
• They allow you to store data in more than one dimension, such as in a grid
or matrix.
• The most common type of multi-dimensional array is the two-dimensional
array, but Java supports arrays with more dimensions.
• int[][] matrix = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
}; // Creates and initializes a 2D array with specified values
48. 2D Array example
public class Simple2DArrayExample {
public static void main(String[] args) {
// Create and initialize a 2x3 matrix
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
// Print the matrix
System.out.println("Matrix:");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}
}
}
49. Multi-Dimensional Arrays with More Than Two Dimensions
3 D Array:
int[][][] threeDArray = new int[3][4][5]; // Creates a 3D array with 3 layers, 4 rows, and 5 columns
int[][][] threeDArray = {
{
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
},
{
{21, 22, 23, 24, 25},
{26, 27, 28, 29, 30},
{31, 32, 33, 34, 35},
{36, 37, 38, 39, 40}
},
{
{41, 42, 43, 44, 45},
{46, 47, 48, 49, 50},
{51, 52, 53, 54, 55},
{56, 57, 58, 59, 60}
}
};
50. Arrays of Objects
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}
// Elements of the array are objects of a class Student.
public class GFG {
public static void main(String[] args)
{
// declares an Array of Student
Student[] arr;
// allocating memory for 5 objects of type Student.
arr = new Student[5];
// initialize the first elements of the array
arr[0] = new Student(1, "aman");
// initialize the second elements of the array
arr[1] = new Student(2, "vaibhav");
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}
51. Jagged Array
• A jagged array is an array of arrays such that member arrays can be of
different sizes. i.e., we can create a 2-D array but with a variable
number of columns in each row.
52. Sample Program
class TestJaggedArray{
public static void main(String[] args){
//declaring a 2D array with odd columns
int arr[][] = new int[3][];
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
//initializing a jagged array
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
//printing the data of a jagged array
for (int i=0; i<arr.length; i++){
for (int j=0; j<arr[i].length; j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();//new line
}
}
}
53. Passing Arrays to Methods
• Like variables, we can also pass arrays to methods.
public class Test {
public static void sum(int[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum += arr[i];
System.out.println("sum of array values : " + sum);
}
public static void main(String args[]) {
int arr[] = { 3, 1, 2, 5, 4 };
// passing array to method method sum
sum(arr);
}
}
54. Returning Arrays from Methods
• As usual, a method can also return an array.
class Test {
public static int[] m1()
{
int [] ar={1,2,3};
return ar;
}
public static void main(String args[])
{
int arr[] = m1();
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i] + " ");
}
}
55. String
• In Java, string is basically an object that represents sequence of char
values.
• String name = "Geeks"; //Also called string literal
• The java.lang.String class is used to create a string object.
• A string acts the same as an array of characters in Java.
• char[] ch={'j','a','v','a'};
• String s=new String(ch); //convert a char array to string
• Above is same as String s=“java”
• We can also create string like this: String s=new String(“Java”);
• In Java, objects of String are immutable which means a constant and
cannot be changed once created.
56. String are immutable
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
}
57. Memory Allotment of String
• Whenever a String Object is created as a literal, the object will be
created in the String constant pool. This allows JVM to optimize the
initialization of String literal.
• String demoString = “Java";
• The string can also be declared using a new operator i.e. dynamically
allocated. In case of String are dynamically allocated they are assigned
a new memory location in the heap. This string will not be added to
the String constant pool.
• String demoString = new String("Geeks");
• String internedString = demoString.intern();
• // this will add the string to string constant pool.
58. Memory Allotment of String
class StringStorage {
public static void main(String args[])
{
// Declaring Strings
String s1 = "TAT";
String s2 = "TAT";
String s3 = new String("TAT");
String s4 = new String("TAT");
// Printing all the Strings
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}
59. Methods of String class
• int length()
• Returns the number of characters in the String.
• "GeeksforGeeks".length(); // returns 13
• Char charAt(int i)
• Returns the character at ith index.
• "GeeksforGeeks".charAt(3); // returns ‘k’
• String substring (int i)
• Return the substring from the ith index character to end.
• "GeeksforGeeks".substring(3); // returns “ksforGeeks”
• String substring (int i, int j)
• Returns the substring from i to j-1 index.
• "GeeksforGeeks".substring(2, 5); // returns “eks”
• String concat( String str)
• Concatenates specified string to the end of this string.
• String s1 = ”Geeks”;
• String s2 = ”forGeeks”;
• String output = s1.concat(s2); // returns “GeeksforGeeks”
60. Methods of String class
• int indexOf(String s)
• Returns the index within the string of the first occurrence of the specified string.
• If String s is not present in input string then -1 is returned as the default value.
• String s = ”Learn Share Learn”;
• int output = s.indexOf(“Share”); // returns 6
• String s = "Learn Share Learn“
• int output = s.indexOf(“Play”); // return -1
• int indexOf(String s, int i)
• Returns the index within the string of the first occurrence of the specified string, starting at the specified index.
• String s = ”Learn Share Learn”;
• int output = s.indexOf("ea",3);// returns 13
• Int lastIndexOf( String s)
• Returns the index within the string of the last occurrence of the specified string.
• If String s is not present in input string then -1 is returned as the default value.
• String s = ”Learn Share Learn”;
• int output = s.lastIndexOf("a"); // returns 14
• String s = "Learn Share Learn"
• int output = s.indexOf(“Play”); // return -1
61. Methods of String class
boolean equals( Object otherObj)
Compares this string to the specified object.
Boolean out = “Geeks”.equals(“Geeks”); // returns true
Boolean out = “Geeks”.equals(“geeks”); // returns false
boolean equalsIgnoreCase (String anotherString)
Compares string to another string, ignoring case considerations.
Boolean out= “Geeks”.equalsIgnoreCase(“Geeks”); // returns true
Boolean out = “Geeks”.equalsIgnoreCase(“geeks”); // returns true
String trim()
Returns the copy of the String, by removing whitespaces at both ends. It does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = word1.trim(); // returns “Learn Share Learn”
String replace (char oldChar, char newChar)
Returns new string by replacing all occurrences of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // return “geeksforgeeks”
boolean contains(CharSequence sequence)
Returns true if string contains contains the given string.
sequence: This is an instance of CharSequence, which is an interface in Java representing a readable sequence of char values. Common
implementations include String, StringBuilder, and StringBuffer.
String s1="geeksforgeeks";
String s2="geeks";
s1.contains(s2) // return true
62. StringBuffer
• StringBuffer is a class in Java that represents a mutable sequence of characters.
• StringBuffer objects are mutable, meaning that you can change the contents of
the buffer without creating a new object.
• The initial capacity of a StringBuffer can be specified when it is created, or it can
be set later with the ensureCapacity() method.
• StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
// Create a StringBuffer with an initial capacity of 20
StringBuffer sb = new StringBuffer(20);
• The append() method is used to add characters, strings, or other objects to the
end of the buffer.
• The insert() method is used to insert characters, strings, or other objects at a
specified position in the buffer.
63. StringBuffer example
public class StringBufferExample {
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer();
sb.append("Hello");
sb.append(" ");
sb.append("world");
String message = sb.toString();
System.out.println(message); // Hello world
}
}
import java.io.*;
class A {
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb); // HJavaello
}
}
64. Advantages of StringBuffer over String
• There are several advantages of using StringBuffer over regular
String objects in Java:
• Mutable: StringBuffer objects are mutable, which means that you can
modify the contents of the object after it has been created. In
contrast, String objects are immutable, which means that you cannot
change the contents of a String once it has been created.
• Efficient: Because StringBuffer objects are mutable, they are more
efficient than creating new String objects each time you need to
modify a string. This is especially true if you need to modify a string
multiple times, as each modification to a String object creates a new
object and discards the old one.
65. Methods of StringBuffer class
• append() method
• The append() method concatenates the given argument with this string.
• StringBuffer sb = new StringBuffer("Hello ");
• sb.append("Java"); // now original string is changed
• System.out.println(sb); //O/P: Hello Java
• insert() method
• The insert() method inserts the given string with this string at the given
position.
• StringBuffer sb = new StringBuffer("Hello ");
• sb.insert(1, "Java");
• // Now original string is changed
• System.out.println(sb); // O/P: HJavaello
66. Methods of StringBuffer class
• replace() method
• The replace(i,j,String s) method replaces the given string from the specified beginIndex and endIndex-1.
• StringBuffer sb = new StringBuffer("Hello");
• sb.replace(1, 3, "Java");
• System.out.println(sb); // O/P: Hjavalo
• delete() method
• The delete(i,j) method of the StringBuffer class deletes the string from the specified beginIndex to endIndex-1.
• StringBuffer sb = new StringBuffer("Hello");
• sb.delete(1, 3);
• System.out.println(sb); // O/P: Hlo
• reverse() method
• The reverse() method of the StringBuilder class reverses the current string.
• StringBuffer sb = new StringBuffer("Hello");
• sb.reverse();
• System.out.println(sb); // O/P: olleH
67. Methods of StringBuffer class
• Char charAt(int index): Retrieves the character at the specified index
• StringBuffer sb = new StringBuffer("Hello");
• char ch = sb.charAt(1); // Gets the character at index 1.
• Void setCharAt(int index, char ch) : Sets the character at the specified
index to the given character ch
• StringBuffer sb = new StringBuffer("Hello");
• sb.setCharAt(1, 'a'); // Changes character at index 1 to 'a‘ O/P: Hallo
• length(): returns length of the StringBuffer object.
• StringBuffer sb = new StringBuffer("Hello, World!");
• int length = sb.length(); // returns 13
• Void ensureCapacity(int minCapacity) : ensure that the capacity of the
StringBuffer is at least equal to the specified minimum capacity.
• StringBuffer sb = new StringBuffer();
• sb.ensureCapacity(50);
68. Methods of StringBuffer class
• capacity() method
• The capacity() method of the StringBuffer class returns the current capacity of
the buffer. The default capacity of the buffer is 16. If the number of characters
increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2.
• For instance, if your current capacity is 16, it will be (16*2)+2=34.
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // default 16
sb.append("Hello");
System.out.println(sb.capacity()); // now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); // Now (16*2)+2=34 i.e
(oldcapacity*2)+2
69. Methods of StringBuffer class
• void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) : Copy
characters from the StringBuffer into a specified character array.
• sourceStart : The starting index (inclusive) of the characters to be copied from the StringBuffer.
• sourceEnd : The ending index (exclusive) of the characters to be copied.
• target: The destination character array where the characters will be copied.
• targetStart: The starting index in the destination array where copying will begin.
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello, World!");
char[] dst = new char[5]; // Array to hold copied characters
// Copy characters from StringBuffer to character array
sb.getChars(0, 5, dst, 0); // Copy "Hello" to dst starting at index 0
// Convert the character array to a string for display
String copiedString = new String(dst);
System.out.println("Copied characters: " + copiedString); // Output: Hello
}
}
70. Enumerated type
• A Java enumeration is class type which serve the purpose of
representing a group of named constants.
enum Level {
LOW,
MEDIUM,
HIGH
}
• Accessing of enum constants : Level myVar = Level.MEDIUM;
• we don’t need to instantiate an enum using new, it has the same
capabilities as other classes.
• Note: unlike classes, enumerations neither inherit other classes nor
can get extended(i.e become superclass).
71. Declaration of enum
• outside the class
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
72. Declaration of enum
• inside a class
public class Test {
enum Color {
RED,
GREEN,
BLUE;
}
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
73. Properties of enum
• Class Type: Every enum is internally implemented using the Class
type.
• Enum Constants: Each enum constant represents an object of type
enum.
• Switch Statements: Enum types can be used in switch statements.
• Implicit Modifiers: Every enum constant is implicitly public static
final. Since it is static, it can be accessed using the enum name. Since
it is final, enums cannot be extended.
• Main Method: Enums can declare a main() method, allowing direct
invocation from the command line.
74. Enum in switch
import java.util.Scanner;
enum Day {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
}
public class Test {
Day day;
// Constructor
public Test(Day d) {
day = d;
}
public void dayIsLike() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-so.");
break;
}
}
public static void main(String[] args) {
String str = "MONDAY";
Test t1 = new Test(Day.valueOf(str));
t1.dayIsLike();
}
}
75. Main Function Inside Enum
• Enums can have a main function, allowing them to be invoked directly from
the command line.
public enum Color {
RED,
GREEN,
BLUE;
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
}
76. Loop through Enum
• We can iterate over the Enum using the values() method,
which returns an array of enum constants.
import java.io.*;
enum Color {
RED,
GREEN,
BLUE;
}
class GFG {
public static void main(String[] args) {
for (Color var_1 : Color.values()) {
System.out.println(var_1);
}
}
}
77. Can an enum have a constructor and methods?
• Yes, an enum in Java can have constructors, methods, and even fields. The constructor is implicitly private.
enum Color {
RED("Red"), GREEN("Green"), BLUE("Blue");
private String colorName;
private Color(String colorName) { // Constructor
this.colorName = colorName;
}
public String getColorName() { // Method
return this.colorName;
}
}
public class EnumExample {
public static void main(String[] args) {
Color color = Color.RED;
System.out.println(color.getColorName()); // Output: Red
}
}
78. Can we have a class with ‘private’ access modifier?
• In Java, classes cannot have the private access modifier when they are declared at the top-level (i.e.,
outside of another class). Top-level classes can only have two access modifiers: public & default.
• However, inner classes (classes defined within another class) can be declared as private. In this case, the
inner class will only be accessible within the enclosing outer class.
// This will result in a compile-time error
private class MyClass {
// Some code
}
public class OuterClass {
private class InnerClass {
// Some code
}
public void accessInner() {
InnerClass obj = new InnerClass(); // This is valid
}
}
// This is not allowed outside OuterClass:
// OuterClass.InnerClass obj = new OuterClass.InnerClass();
// Error