Java Objects and Classes Explained
Java Objects and Classes Explained
An object in Java is an instance of a class that represents a real-world entity. Objects are key to
understanding object-oriented technology. An entity that has state and behavior is known as an
object for instance chair, bike, marker, pen, table, car etc. It can be physical or logical (tangible
and intangible). The example of intangible object is banking system.
It consists of:
1. State (Attributes/Fields/Properties)
o Represented by instance variables (data members).
o Stores object-specific information.
o represents data (value) of an object.
2. Behavior (Methods/Functions)
o Represented by functions (methods).
o Defines actions that the object can perform.
o Represents the behavior (functionality) of an object such as deposit, withdraw etc.
3. Identity (Unique Existence in Memory)
o Every object has a unique memory location.
o Multiple objects of the same class can exist independently.
o Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify
each object uniquely.
1|Page
class Car {
// Instance Variables (Attributes)
String brand;
String model;
String color;
// Method (Behavior)
void displayInfo() {
[Link]("Car Brand: " + brand + ", Model: " + model + ", Color: " + color);
}
}
2|Page
Explanation of Java Object Example
Real-World Analogy
Think of a class as a blueprint and objects as houses built from the blueprint:
Objects are stored in the Heap Memory. Heap memory is largest memory area in JVM.
It used to store objects and class instances. Garbage Collector (GC) automatically
removes unused objects to free up space
References (car1, car2) point to objects in the heap.
Example:
3|Page
Different Ways to Create Objects in Java
1. this Keyword
[Link] = brand;
2. Garbage Collection
4|Page
car1 = null; // Eligible for garbage collection
void modifyCar(Car c) {
[Link] = "Black"; // Modifies the object
}
Software objects
Software objects are conceptually similar to real-world. Objects: they too consist of state and
related behavior. An object stores its state in fields (variables in some programming languages)
and exposes its behavior through methods (functions in some programming languages). Methods
operate on an object's internal state and serve as the primary mechanism for object-to-object
communication
Bundling code into individual software objects provides a number of benefits, including:
5|Page
Modularity in Java refers to the structuring of code into separate, reusable, and independent
components (modules). It improves code organization, maintainability, and reusability.
class User {
[Link] = name;
[Link] = age;
6|Page
// Main class (Separate module)
[Link] = name;
7|Page
Step 2: Import and Use the Package in another Class
Key Characteristics:
8|Page
public class Main {
public static void main(String[] args) {
new Calculator().square(5); // Anonymous object used to call square method
}
}
new Calculator().square(5);
o Creates an object of Calculator without assigning it to a variable.
o Calls the square() method with the argument 5.
o The object is not reusable and will be destroyed after execution.
class Message {
void show() {
[Link]("Hello from an Anonymous Object!");
}
}
An anonymous class is an unnamed class that is declared and instantiated in a single expression.
9|Page
public class Main {
public static void main(String[] args) {
// Anonymous object of an anonymous class
new Animal() {
void makeSound() {
[Link]("Woof! Woof! (Anonymous Object)");
}
}.makeSound(); // Calls method immediately
}
}
Class
Class in Fundamental Java
In Java, a class is a blueprint for creating objects. It defines the properties (fields/variables) and
behaviors (methods) that an object of that class can have. A class is a fundamental concept in
Object-Oriented Programming (OOP) and helps in encapsulation, inheritance, and
polymorphism.
10 | P a g e
A class is declared using the class keyword:
class ClassName {
DataType variableName;
// Constructor
ClassName() {
// Initialization code
returnType methodName() {
// Method body
The public keyword indicates that this class is available for use by other classes. Although it is
optional, you usually include it on your class declarations. The ClassName is an identifier that
provides a name for your class. You can use any identifier the name a class use the following three
mechanisms:
Begin the class name with a capital letter. If the class name consists of more than one
word, begin each word with capital. For example, Ball, Car, Dog, Bicycle, RetailCustomer
11 | P a g e
Classes create objects, and nouns are the words you use to identify objects. Thus, most
class names should be nouns.
Avoid using the name of a Java API class. This is not must, but if you create a class that
has the same name as a Java API class, you have to use fully qualified names (like
[Link]) to tell your class and the API class with the same name apart.
Let's create a simple class named Car, with attributes (brand, model, year) and a method
(displayCarDetails()).
12 | P a g e
Car car2 = new Car("Honda", 140);
Verification:
An instance variable in Java is a variable that belongs to an instance (object) of a class. These
variables are declared inside a class but outside any method, constructor, or block.
1. Instance-Specific: Each object of the class has its own copy of the instance variable.
13 | P a g e
2. Scope: They are accessible within the class but can have different access modifiers
(private, protected, public, or default).
3. Memory Allocation: They are stored in the heap memory as part of the object.
4. Default Values: If not initialized explicitly, they take default values (e.g., 0 for int, null
for objects).
5. Accessed via Object: They are accessed using the object reference.
// Constructor
Car(String brand, int speed) {
[Link] = brand;
[Link] = speed;
}
14 | P a g e
brand and speed are instance variables because they belong to each instance (object) of
the Car class.
Each object (car1, car2) has its own copy of brand and speed.
The constructor initializes the instance variables when an object is created.
The display() method prints the values of instance variables for each object.
Methods in Java
A method in Java is a block of code that performs a specific task. It is used to define the behavior
of an object and can be reused multiple times.
15 | P a g e
// Creating an object to call the instance method
Calculator calc = new Calculator();
int sum = [Link](10, 5);
[Link]("Sum: " + sum);
Explanation:
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as [Link](), but you can
also create your own methods to perform certain actions:
16 | P a g e
ReturnType → The type of value the method returns (e.g., int, void).
MethodName → The name of the method (follows camelCase naming convention).
Parameters → Inputs (optional) to the method.
Return → If the method has a return type, it must return a value.
Sum: 15
Hello! Welcome to Java Methods.
Explanation:
17 | P a g e
Call method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon.
In the following example, myMethod() is used to print a text (the action), when it is called.
Example: Inside Student, call the myMethod() method:
Static Method
Belongs to the class rather than an instance. It can be called without creating an object. It can’t
access instance variables or non-static methods directly. Commonly used for utility functions.
Example:
class MathUtil {
static int add(int a, int b) { // Static method
return a + b;
18 | P a g e
}
}
Public Method
Example:
class Calculator {
public int multiply(int a, int b) { // Public method
return a * b;
}
}
1. Method Parameters
A method parameter is a placeholder for the value that will be provided when the method is
called.
Example:
19 | P a g e
class MathUtil {
// 'a' and 'b' are parameters
public int add(int a, int b) {
return a + b;
}
}
2. Method Arguments
Example:
When passing primitive types (e.g., int, double), Java passes a copy of the value.
class Example {
void modify(int x) {
x = x + 10;
[Link]("Inside method: " + x);
}
}
20 | P a g e
}
}
Output:
Inside method: 30
Outside method: 20
The original value of num remains unchanged because primitives are passed by value.
class Example {
void modify(StringBuilder sb) {
[Link](" World");
}
}
Output:
Explanation: Since StringBuilder is a reference type, changes inside the method affect the
original object.
If the number of arguments is unknown, we use varargs (variable-length arguments) with ...
(ellipsis).
class VarArgsExample {
21 | P a g e
void sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
[Link]("Sum: " + total);
}
}
Output:
Sum: 10
Sum: 30
Parameters vs. Arguments
Feature Parameters Arguments
Values passed when calling
Definition Variables in method definition
method
Scope Exists only inside the method Exists outside the method
Example void sum(int a, int b) sum(5, 3);
Cannot change outside the Can affect original object (for
Mutability
method (for primitives) references)
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value.
If you want the method to return a value, you can use a primitive data type (such as int, char, etc.)
instead of void, and use the return keyword inside the method:
class MathUtil {
22 | P a g e
}
class Logger {
[Link]("Application started.");
In Java, an object must be initialized before it can be used. There are several ways to initialize
an object:
Constructors are special methods used to initialize objects when they are created.
Example:
23 | P a g e
class Person {
String name;
int age;
// Constructor
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
}
Output:
Instance Initializer Blocks ({}) run before the constructor and are used to initialize instance
variables.
Example:
class Person {
String name;
int age;
24 | P a g e
public class Main {
public static void main(String[] args) {
Person p = new Person(); // No constructor needed
[Link]("Name: " + [Link] + ", Age: " + [Link]);
}
}
Output:
Static blocks are used to initialize static variables before any object is created.
Example:
class Config {
static String appName;
// Static block
static {
appName = "My Application";
}
}
Output:
Example:
class Car {
25 | P a g e
String model;
int year;
void setModel(String model) {
[Link] = model;
}
void setYear(int year) {
[Link] = year;
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
[Link]("Toyota");
[Link](2022);
The newInstance() method of the Class class allows dynamic object creation.
Example:
package instance;
import [Link];
import [Link];
try {
26 | P a g e
Instance p = [Link](); // Using reflection
} catch (InstantiationException e) {
[Link]();
} catch (IllegalAccessException e) {
[Link]();
Output:
Example:
class Employee {
String name;
// Factory method
public static Employee createEmployee(String name) {
return new Employee(name);
}
}
27 | P a g e
[Link]("Employee Name: " + [Link]);
}
}
Output:
Example:
class Student implements Cloneable {
String name;
Student(String name) {
[Link] = name;
}
Output:
Original: Daniel
Clone: Daniel
28 | P a g e
Example:
import [Link].*;
Person(String name) {
[Link] = name;
}
}
29 | P a g e
Access level modifiers
Access level modifiers determine whether external classes can use a particular field or invoke a
particular method of the class being defined. There are two levels of access control:
A class may be declared with the modifier public, in which case that class is visible to all classes
everywhere.
If a class has no modifier (the default, also known as package-private), it is visible only within its
own package (packages are named groups of related classes).
The following table shows the access to members permitted by each modifier.
Data Members
There are several kinds of variables in classes such as Member variables in a class—these are
called fields; Variables in a method or block of code—these are called local variables; Variables
in method declarations—these are called parameters. A data member is a variable that is defined
in the body of a class, outside of any of the class’ methods. Fields are available to all the methods
30 | P a g e
of a class. In addition, if the data member/field specifies the public keyword, then it is visible
outside of the class. • If it don’t want the field to be visible outside of the class, use the private
keyword instead.
Constructors
Constructor in java is a special type of method that is used to initialize the object. Java constructor
is invoked at the time of object creation. It constructs the values i.e. provides data for the object
that is why it is known as constructor. Rules for creating java constructor: there are basically two
rules defined for the constructor. Constructor name must be same as its class name. Constructor
must have no explicit return type.
Constructors have no return type, not even void. This is because the implicit return type of a class’s
constructor is the class type itself. Broadly, constructors can be divided into three: default
constructor, parameterized constructor and copy constructor.
Default Constructors
If don’t define a constructor in the class of java creates one of it. This generated constructor is
called the default constructor. A constructor that have no parameter is known as default
constructor.
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.
class Bike1{
Bike1(){[Link]("Bike is created");}
}
31 | P a g e
Output:
Bike is created
Parameterized Constructors
Copy constructor can be seen one type of parameterized constructor. A constructor that has
parameters is known as parameterized constructor. Parameterized constructor is used to provide
different values to the distinct objects. It initializes the object to the values of the parameter passed
when new keyword is used to create object.
Syntax of copy parameters constructor: <className> (data type variable comma datatype
variableName){}
class Student {
String id;
String name;
//parameterized constructor
id = i;
name = n;
32 | P a g e
[Link]();
[Link]();
Copy Constructor
Another common form of a constructor is called a copy constructor. A copy constructor is a special
constructor for creating a new object as a copy of an existing object. The first argument of such a
constructor is a reference to an object of the same type as is being constructed, which might be
followed by parameters of any type. Once it gets its object argument, creates a copy of it and create
new object.
class Student6{
int id;
String name;
id = i;
name = n;
Student6(Student6 s){
id = [Link];
name =[Link];
33 | P a g e
Student6 s2 = new Student6(s1);
[Link]();
[Link]();
Destructors
Unlike C++, Java does not have destructors because Java has automatic garbage collection (GC).
Instead of explicitly defining destructors, Java relies on the Garbage Collector (GC) to reclaim
memory when objects are no longer needed. However, Java provides a method called finalize()
(deprecated in Java 9 and removed in Java 18) that used to act like a destructor. Java 9 finalize()
was deprecated (still usable but with warnings). Java 18 finalize() was completely removed.
@Override is an annotation in Java that ensures a method in a subclass properly overrides a
method in a superclass. It helps prevent errors when overriding methods.
Since Java does not have destructors, It use the following techniques for resource cleanup:
1. Garbage Collection (GC): Automatically reclaims memory used by objects that are no
longer accessible.
4. Explicit Cleanup Methods: Manually defined methods (close(), dispose(), etc.) for
cleanup.
class MyClass {
34 | P a g e
// Constructor
MyClass() {
[Link]("Constructor is called!");
@Override
[Link]();
} }
Constructor is called!
End of main method!
Destructor (finalize) is called!
Note:
The call to [Link]() requests garbage collection but does not guarantee immediate
execution.
finalize() is deprecated in Java 9 and removed in Java 18.
35 | P a g e
Example 2: Using AutoCloseable with try-with-resources (Preferred for Resource Cleanup)
Since Java does not support destructors, the best way to release resources like files or database
connections is to implement the AutoCloseable interface and use the try-with-resources block.
// Constructor
MyResource() {
[Link]("Resource acquired!");
@Override
[Link]("Resource released!");
36 | P a g e
Output
Resource acquired!
Resource released!
In Java, Console I/O (Input/Output) is used to interact with the user through the command-line
interface (CLI). It involves:
Output
Hello, Java!
37 | P a g e
Welcome to Console I/O in [Link] score is: 95
%d integer
%f real number
%s string
printf does not drop to the next line unless you write \n
The Scanner class is the most commonly used method for user input. Communicates with
[Link]
import [Link];
38 | P a g e
int age = [Link](); // Reads integer
[Link]("\nUser Details:");
Sample Output
User Details:
Age: 30
Salary: $45000.75
39 | P a g e
import [Link];
import [Link];
import [Link];
[Link]("\nHello, " + name + "! You are " + age + " years old.");
[Link]();
Sample Output
import [Link];
40 | P a g e
public static void main(String[] args) {
if (console == null) {
return;
Output (Example)
Welcome, user123!
In Java, strings are used to store and manipulate sequences of characters. Unlike other
programming languages where strings are arrays of characters, Java treats strings as objects of
the String class, which is part of [Link] package.
41 | P a g e
public class StringExample {
[Link](str1);
[Link](str2);
Output
Hello, Java!
Hello, Java!
String literals are stored in the string pool, making them memory-efficient.
Using new String() creates a new object in heap memory, which is less efficient.
2. String Immutability
Thread Safety: Multiple threads can use the same string without risk.
String Pool Optimization: Saves memory by storing only one copy of each string literal.
42 | P a g e
public static void main(String[] args) {
Output
Java
Since strings are immutable, [Link](" Programming") creates a new string, but str still holds
"Java". To modify, store the result:
3. String Methods
43 | P a g e
public class StringMethods {
Output
Length: 20
Substring: 'Java'
4. String Comparison
1. == vs .equals()
44 | P a g e
public class StringComparison {
String s1 = "Java";
String s2 = "Java";
Output
true
false
true
45 | P a g e
public class MutableStrings {
[Link](5, 7, "was");
Output
Java Programming
Java is Programming
46 | P a g e
Example: Type Conversion
Output
150
42 is a number
47 | P a g e
Declaration of CharSequence Interface
public interface CharSequence {
char charAt(int index); // Returns the character at the given index
int length(); // Returns the length of the sequence
CharSequence subSequence(int start, int end); // Extracts part of the sequence
String toString(); // Converts to a String
}
2. Classes Implementing CharSequence
Class Mutable Thread-Safe Usage
String ❌ No ✅ Yes (Immutable) Fixed character sequences
StringBuilder ✅ Yes ❌ No Fast string modifications
StringBuffer ✅ Yes ✅ Yes (Synchronized) Thread-safe string modifications
Since CharSequence is an interface, it cannot be instantiated directly, but we can assign different
implementations (String, StringBuilder, etc.) to a CharSequence variable.
48 | P a g e
4. Methods of CharSequence
49 | P a g e
General Unlike substring(), subSequence() returns another CharSequence.
50 | P a g e
Polymorphism allows flexible handling of character sequences.
The matches() method in String works only on String, but we can use Pattern with
CharSequence.
51 | P a g e
In Java, comparing strings is fundamental because strings are objects and not just primitive data
types. The equals() method is the recommended way to compare strings based on content rather
than memory reference.
In Java:
52 | P a g e
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = [Link]();
if (n == [Link]()) {
char v1[] = [Link]();
char v2[] = [Link]();
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
3. Case-Sensitive Comparison
53 | P a g e
String s1 = "Java";
String s2 = "java";
[Link]([Link](s2)); // false (case-sensitive)
}
}
Output
False
"Java" and "java" are different because uppercase 'J' and lowercase 'j' are different characters.
4. Case-Insensitive Comparison (equalsIgnoreCase())
The compareTo() method in Java is used to compare two strings lexicographically. It is part of
the Comparable interface and is commonly used for sorting strings.
1. Understanding compareTo()
The compareTo() method belongs to the String class and is defined as: public int
compareTo(String anotherString)
How it Works?
54 | P a g e
Returns 0 → If both strings are equal.
Returns a positive value (> 0) → If the first string is greater than the second string.
Returns a negative value (< 0) → If the first string is less than the second string.
Sorting Order
3. Case-Sensitive Comparison
compareTo() is case-sensitive, meaning uppercase and lowercase letters are treated differently.
55 | P a g e
[Link]([Link](s2)); // Negative (-ve) value (uppercase < lowercase)
}
}
Output -32
"Java" is less than "java" because uppercase 'J' (Unicode 74) comes before lowercase 'j'
(Unicode 106).
Unicode difference: 74 - 106 = -32.
The compareTo() method is useful for sorting strings in ascending or descending order.
[Link]([Link](languages));
}
}
Output
[C, Java, Python, Ruby]
56 | P a g e
Lexicographical order: "C" < "Java" < "Python" < "Ruby".
"Apple" is greater than "Ape" because 'p' has a higher Unicode value than 'e'.
57 | P a g e
[Link]([Link](s2)); // true (Exact match)
[Link]([Link](s3)); // Negative (-ve) value (Apple < Banana)
}
}
Output
true
-1
Example
public class StringConcat {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = " World";
String result = s1 + s2;
Example
public class ConcatMethod {
58 | P a g e
public static void main(String[] args) {
String s1 = "Hello";
String s2 = " Java";
String result = [Link](s2);
[Link](result); // Output: Hello Java
}
}
Example
public class JoinExample {
public static void main(String[] args) {
String result = [Link](", ", "Java", "Python", "C++");
[Link](result); // Output: Java, Python, C++
}
}
Example
public class FormatExample {
public static void main(String[] args) {
String name = "John";
int age = 25;
String result = [Link]("My name is %s and I am %d years old.", name, age);
[Link](result);
59 | P a g e
}
}
Substring in Java
The substring() method in Java is used to extract a part of a string. It is a very useful method when
you need to retrieve a portion of a string, based on a starting index or a range of indices.
1. Syntax of substring()
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
Parameters:
Example
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
String result = [Link](7); // From index 7 to the end
[Link](result); // Output: World!
}
}
3. Example 2: Using substring(int beginIndex, int endIndex)
Example
public class SubstringExample {
public static void main(String[] args) {
String str = "Hello, World!";
String result = [Link](7, 12); // From index 7 to 11
60 | P a g e
[Link](result); // Output: World
}
}
Note:
Both toUpperCase() and toLowerCase() are methods in the String class used to convert the case
of characters in a string.
1. toUpperCase() Method
Syntax:
public String toUpperCase()
Example:
public class ToUpperCaseExample {
public static void main(String[] args) {
String str = "hello, world!";
String result = [Link]();
[Link](result); // Output: HELLO, WORLD!
}
}
2. toLowerCase() Method
Syntax:
public String toLowerCase()
Example:
public class ToLowerCaseExample {
public static void main(String[] args) {
61 | P a g e
String str = "HELLO, WORLD!";
String result = [Link]();
[Link](result); // Output: hello, world!
}
}
Note:
Both methods do not modify the original string; they return a new string with the
desired case.
These methods are locale-insensitive, meaning they apply case conversion based on the
default locale of the JVM.
The trim() method in Java is used to remove leading and trailing whitespace (spaces, tabs, etc.)
from a string.
Syntax:
public String trim()
Parameters:
Returns:
Example:
public class TrimExample {
public static void main(String[] args) {
String str = " Hello, World! ";
String result = [Link]();
[Link](result); // Output: "Hello, World!"
}
}
Note:
62 | P a g e
Does not remove internal spaces between words.
Returns a new string, the original string remains unchanged.
The charAt() method in Java is used to retrieve the character at a specified index in a string.
Syntax:
public char charAt(int index)
Parameters:
Returns:
Example:
In Java, several methods are available to search for a substring or a character within a string. These
methods help you locate the position of a substring or check for its existence.
1. indexOf() Method
The indexOf() method is used to find the first occurrence of a character or a substring within a
string.
Syntax:
public int indexOf(int ch) // For character
public int indexOf(String str) // For substring
Returns:
63 | P a g e
The index of the first occurrence of the character or substring.
Returns -1 if not found.
Example:
public class IndexOfExample {
public static void main(String[] args) {
String str = "Hello, World!";
int index = [Link]("World");
[Link](index); // Output: 7
}
}
2. lastIndexOf() Method
Syntax:
public int lastIndexOf(int ch) // For character
public int lastIndexOf(String str) // For substring
Returns:
Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello, World, Hello!";
int index = [Link]("Hello");
[Link](index); // Output: 14
}
}
3. contains() Method
Syntax:
public boolean contains(CharSequence sequence)
64 | P a g e
Returns:
Example:
public class ContainsExample {
public static void main(String[] args) {
String str = "Hello, World!";
boolean result = [Link]("World");
[Link](result); // Output: true
}
}
4. startsWith() and endsWith() Methods
Syntax:
public boolean startsWith(String prefix)
public boolean endsWith(String suffix)
Example:
public class StartsEndsWithExample {
public static void main(String[] args) {
String str = "Hello, World!";
boolean starts = [Link]("Hello");
boolean ends = [Link]("World!");
[Link](starts); // Output: true
[Link](ends); // Output: true
}
}
5. matches() Method
The matches() method is used to check if a string matches a regular expression pattern.
Syntax:
65 | P a g e
public boolean matches(String regex)
Example:
public class MatchesExample {
public static void main(String[] args) {
String str = "Hello123";
boolean result = [Link]("[A-Za-z0-9]+");
[Link](result); // Output: true
}
}
Replacing Parts of a String in Java
Java provides methods to replace parts of a string. These methods allow you to replace characters
or substrings within a string.
1. replace() Method
The replace() method replaces all occurrences of a specified character or substring with a new
character or substring.
Syntax:
public String replace(char oldChar, char newChar)
public String replace(CharSequence target, CharSequence replacement)
2. replaceAll() Method
The replaceAll() method replaces substrings that match a regular expression with a specified
replacement.
Syntax:
66 | P a g e
public String replaceAll(String regex, String replacement)
Example:
String str = "abc123xyz";
String result = [Link]("[0-9]", "#");
[Link](result); // Output: abc###xyz
3. replaceFirst() Method
The replaceFirst() method replaces the first occurrence of a substring that matches a regular
expression.
Syntax:
Example:
String str = "abc123abc";
String result = [Link]("abc", "xyz");
[Link](result); // Output: xyz123abc
Finding Length of a String in Java
In Java, the length of a string can be determined using the length() method.
1. length() Method
The length() method returns the number of characters in a string, including spaces.
Syntax:
public int length()
Returns:
Example:
public class StringLengthExample {
public static void main(String[] args) {
String str = "Hello, World!";
int length = [Link]();
[Link](length); // Output: 13
67 | P a g e
}
}
The length() method is a simple and effective way to get the size of a string in Java. It returns the
total number of characters, including any whitespace.
The Math class in Java is a utility class that provides a collection of static methods for performing
basic mathematical operations such as exponentiation, logarithms, trigonometry, and more.
[Link](-10); // Output: 10
2. pow() – Power
Returns the value of the first argument raised to the power of the second argument.
68 | P a g e
Returns a random double between 0.0 (inclusive) and 1.0 (exclusive).
7. round() – Rounding
[Link](2.5); // Output: 3
Generally , The Math class provides essential mathematical functions like finding absolute values,
powers, square roots, and generating random numbers. All methods in the Math class are static, so
they are used directly with the class name.
Encapsulation in Java
1. Private Variables:
Data (fields) of a class are marked as private, making them inaccessible outside the class.
This ensures that the data is protected from direct modification.
2. Public Methods (Getters and Setters):
Public methods (known as getters and setters) are provided to access and update the
values of private variables.
Example:
public class Person {
// Private field
private String name;
private int age;
69 | P a g e
// Setter for name
public void setName(String name) {
[Link] = name;
}
Data Protection: By making fields private, direct modification is prevented, ensuring data
integrity.
Controlled Access: Getters and setters allow validation or additional logic when accessing or
modifying data.
Flexibility: Changes to internal implementation can be made without affecting external code, as
long as the interface remains the same.
Therefore, Encapsulation in Java involves using private fields and public getter/setter methods
to control access to an object's data. It ensures that the internal state is protected and only
modified in controlled ways, promoting better maintainability and security.
70 | P a g e
71 | P a g e