0% found this document useful (0 votes)
38 views20 pages

Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views20 pages

Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Class fundamentals

 In Java, a class is a blueprint or prototype from which objects are


created. It is a user-defined data type that encapsulates data and
methods that operate on that data. A class can be thought of as a
template for creating objects.
 Here’s an example of how to declare a class in Java:
public class MyClass {

// fields

Private int myField;

// constructor

Public MyClass(int myField) {

this.myField = myField;

// methods

Public int get MyField() {


return myField;
}
public void setMyField(intmyField) {
this.myField = myField;
}
}
In this example, we define a class called “Myclass” that has a single field called
“myField”. We also define a constructor that takes an integer argument and sets the
value of “myField”.Finally, we define two methods: “getMyField()” and
“setMyField()”, which get and set the value of “myField”, respectively.
Defining a Class
 A Class is a set of properties or methods that are common to all Objects of
one type
 Class declaration can include these components:
1. Modifiers: A class can be “Public”, ”Private” or
“Protected”
2. Class name: Thename of the class and it is user defined.
3. Body: The class body surrounded by braces,{ }.
 Syntax:
class<class_name>
{
Variables;
Methods;
}

Creating Objects
 Object is a basic unit of Object-Oriented Programming and represents the real
life entities.
 Declaring object is also called instantiating a class.
 When an object of a class is created, the class is said to be instantiated.
 All the instances share the attributes and the behavior of the class. But the
values of those attributes, i.e. the state are unique for each object. A single class
may have any number of instances.
 The general syntax for creating object is as follows:
Classname objectname; //declaration of object
Objectname = new classname (); //object instantiation
 The above statement has three parts which is discussed in the detail below:
1. Declaration: The code set in the bold are all variable declarations that
associate a variable name with an object type.
2. Instantiation: The new keyword is a Java operator that creates the
object.
3. Initialization: The new operator is Followed by a call to a constructor,
which initializes the new object.

Assigning object Reference Variables


In Java, an object reference variable is a variable that stores the memory address of
an object. When you create an object in Java, the JVM allocates memory for the
object and returns the memory address of the object. You can then store this memory
address in an object reference variable.

Here’s an example of how to declare and initialize an object reference variable in


Java:

// Declare an object reference variable

MyObject myObject;

// Create an object and assign its memory address to the reference variable

myObject = new MyObject();

In this example, “MyObject” is the class of the object we want to create. We first
declare an object reference variable “myObject” of type “MyObject”. We then create
a new object of type “MyObject” suing the “new” keyword and assign its memory
address to “myObject”.

Introduction to method, Accessing class members


 In Java, methods are blocks of code within a class that perform specific tasks
or actions. They are used to define the behavior of objects created from that
class. Methods are essential for encapsulating the logic associated with a class
and allowing controlled access to class members. Here's an introduction to
methods and how to access class members in Java:
 Defining a Method:
To define a method in Java, you need to specify its return type, name, and any
parameters it takes (if applicable). Here's the basic syntax:
return_type method_name(parameters)
{
// Method body
// Perform actions and calculations
// Optionally, return a value using the 'return' statement
}
• “return_type”: The data type of the value the method returns. Use
‘void’ if the method doesn't return a value.
• “method_name”: The name of the method, following Java naming
conventions.
• “Parameters”: A list of input parameters (if any) that the method
accepts.

 Accessing Class Members:


To access class members (fields and methods), you need to create an object
(instance) of the class and use the object to access the members using the dot
(‘.’) notation.
 Example:
Calculator calculator = new Calculator(); // Create an object of the class
int sum = calculator.add(5, 3); // Call the 'add' method using the object
System.out.println("Sum: " + sum);
 In this example, we create an instance of the ‘Calculator’ class named
‘calculator’ and use it to call ‘add’ the method, passing two integers as
arguments. The result is stored in the ‘sum’variable and displayed using
‘System.out.println();’.
 Calling Methods:

Methods are called using the object followed by the method name and any
required arguments in parentheses. If the method doesn't return a value, you
simply call it without assigning the result.
calculator.someMethod(); // Calling a method without a return value
Constructors, Characteristics of Constructors
 Constructor:
A constructor initializes an object at the time of creation. It has the same name as the
class in which it resides. The constructor is automatically called when the object is
created, before the new operator completes. Constructors have no return type, not
even void. This is because the implicit return type of a class’ constructor is the class
type itself. It is the constructor’s job to initialize the internal state of an object so that
the code creating an instance will have a fully initialized, usable object immediately.
There are three rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final
 Characteristics of Constructor:
1. A constructor has the same name as the class it belongs to.
2. A constructor has no return type, not even void.
3. A constructor is called automatically when an object is created using the
new keyword.
4. If a class does not have any constructors defined, the Java compiler
provides a default constructor with no arguments.
5. A class can have multiple constructors with different parameter lists.
This is called constructor overloading.
Types of constructors
There are four types of constructors in Java:
 Default constructor: If not implemented any constructor by the
programmer in a class, Java compiler inserts a default constructor with
empty body into the code, this constructor is known as default constructor.
If user defines any parameterized constructor, then compiler will not create
default constructor and vice versa if user don’t define any constructor, the
compiler creates the default constructor by default during compilation.
 no-arg constructor: Constructor with no arguments is known as no-arg
constructor. The signature is same as default constructor; however body
can have any code unlike default constructor where the body of the
constructor is empty.
 Parameterized constructor: Constructor with arguments is known as no-
arg constructor. The signature is same as default constructor; however body
can have any code unlike default constructor where the body of the
constructor is empty.
Copy constructor: A constructor that initializes an object using another object of the
same class is known as a copy constructor. The copy constructor is used to create a
new object with the same values as an existing object.

this Keyword
 “this” is a reference to object itself. ‘this’ keyword can be used to refer current
class instance variables, to invoke current class constructor, to return the
current class instance, as method parameter, to invoke current class method and
as an argument in the constructor call. “this” keyword when used in a
constructor can only be the first statement in Constructor and constructor can
have either this or super keyword but not both.
 Example:
class A
{
int a=10;
public void show()
{
double a=100.200;
System.out.println(“Value of A is : “+a);
}
}
 The above program code will display “Value of A is : 100.200”, because the
preference will always go to local variable or the variable with immediate
scope. System.out.println(“Value of A is : “+this.a); The above statement will
display “Value of A is: 10”, because the reference “this” will point to current
instance variable “a” of the class.

Java Destructor- Garbage Collection


 In Java, there is no concept of destructors like in some other programming
languages (e.g., C++). Instead, Java relies on automatic memory management
through a process called garbage collection. Garbage collection is the
mechanism by which Java automatically deallocates memory that is no longer
in use, effectively cleaning up objects that are no longer accessible. Here's an
overview of how garbage collection works in Java:
 Garbage Collection Process:
1. object Creation: When you create an object in Java using the ‘new’
keyword, memory is allocated for that object on the heap.
MyClassobj = new MyClass();
1. Object Reference: Objects are accessed through references in Java.The
‘obj’ reference points to the newly created object in memory.
2. Reference Count: The Java Virtual Machine (JVM) keeps track of how
many references point to each object. When an object no longer has any
references pointing to it, it becomes eligible for garbage collection.
3. Garbage Collection: Periodically, the JVM's garbage collector identifies
objects that are no longer reachable (i.e., no references point to them).
These objects are considered garbage and are scheduled for removal
from memory.
• The exact algorithm and timing of garbage collection may vary
depending on the JVM implementation (e.g., the Oracle HotSpot
JVM).
4. Memory Reclamation: When an object is identified as garbage, its
memory is automatically reclaimed by the garbage collector, making it
available for future object allocations.

Finalize( ) Method
 It is difficult for the programmer to forcefully execute the garbage collector to
destroy the object. But Java provides an alternative way to do the same. The
Java Object class provides the finalize() method that works the same as the
destructor. The syntax of the finalize() method is as follows:
 Syntax:
protected void finalize throws Throwable()
{
//resources to be close
}
 It is not a destructor but it provides extra security. It ensures the use of external
resources like closing the file, etc. before shutting down the program. We can
call it by using the method itself or invoking the method System.run
Finalizers OnExit(true).
o It is a protected method of the Object class that is defined in the
java.lang package.
o It can be called only once.
o We need to call the finalize() method explicitly if we want to override
the method.
o The gc() is a method of JVM executed by the Garbage Collector. It
invokes when the heap memory is full and requires more memory for
new arriving objects
o Except for the unchecked exceptions, the JVM ignores all the exceptions
that occur by the finalize() method.
Overloading methods
 Method Overloading is a mechanism in which a class allows more than one
method with same name but with different prototype.
 Multiple methods can be created by changing the no. of parameters, type of
parameters, order of parameters or combination of any.
 The method binding is done by the compiler at compile time and fix the calling
method based on the actual parameter matching or by using implicit type
conversion.
 This is also called as static binding, early binding or compile time
polymorphism.

Overloading constructors
Constructor Overloading:
 Sometimes there is a need of initializing an object in different ways. This can
be done using constructor overloading.
 E.g. A frame object can be created using default constructor or using title of the
frame.
 Multiple constructors can be created by changing the no. of parameters, type of
parameters, order of parameters or combination of any.

Using objects as parameters


 In Java, objects can be passed as parameters to methods. When passing an
object as a parameter to a method, a reference to the object is passed rather
than a copy of the object itself. This means that any modifications made to the
object within the method will have an impact on the original object .
 Here’s an example of how to pass an object as a parameter in Java:
public class MyClass {
// fields
Private int myField;
// constructor
Public MyClass(int myField) {
this.myField = myField;
}
// method with object as parameter
public void myMethod(MyClassobj) {
// block of code to define this method
}
// more methods
}
 In this example, MyClass is the class of the object we want to pass as a
parameter. We first declare an object reference variable obj of type MyClass.
We then pass this object as a parameter to the method myMethod().

Argument Passing
 In Java, when you pass arguments to a method, they are transferred as copies
of the original values, and the method operates on these copies. Understanding
how arguments are passed in Java is crucial for understanding how methods
work. There are two types of argument passing in Java:
1) Pass by Value:
In Java, all arguments for primitive data types (such as `int`, `float`, `char`,
etc.) are passed by value. This means that a copy of the value is passed to the
method, and any changes made to the parameter inside the method do not
affect the original value.
1) Pass by Reference:
In Java, all objects (instances of classes) are passed by reference. This means
that when you pass an object to a method, you are passing a reference to the
same object in memory. Changes made to the object's state inside the method
are reflected in the original object.

Returning Objects
 In Java, a method can return any type of data, including objects. When a
method returns an object, the return type of the method is the name of the class
to which the object belongs. Here’s an example of how to return an object from
a method in Java:
// method that returns an object

Public MyClass getMyObject() {


return new MyClass(myField);

// more methods

 In this example, MyClass is the class of the object we want to return. We first
define a constructor that takes an integer argument and sets the value of
myField. We then define a method called getMyObject() that returns a new
instance of MyClass with the same value of myField.
 To use the returned object, you can create an object reference variable and
assign the result of the method call to it, like this:
MyClass myObject = new MyClass(42).getMyObject();
Recursion
Java supports recursion. Recursion is the process of defining something in terms of
itself. As it relates to Java programming, recursion is the attribute that allows a
method to call itself. A method that calls itself is said to be recursive.
The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole number between 1 and N. For
example, 3 factorial is 1*2*3, or 6. Here is how a factorial can be computed by use of
recursive method:
Example:
Class Factorial{
Int fact(int n){
Int result;
If(n==1)
return 1;
result= fact(n-1)*n;
Return result;
}
}
Class Recursion {
Public static void main(String args[]) {
Factorial f= new Factorial();
System.out.println(“Factorial of 3 is” + f.fact(3));
System.out.println(“Factorial of 4 is” + f.fact(4));
System.out.println(“Factorial of 5 is” + f.fact(5));
}
}
 Access control in Java is managed through the use of access modifiers. These
modifiers help to restrict the scope of a class, constructor, variable, method, or
data member. There are four types of access modifiers in Java:
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: If you don’t specify any access level, it will be the default. The
access level of a default modifier is only within the package. It cannot be
accessed from outside the package.
3. Protected: The access level of a protected modifier is within the
package and outside the package through a child class. If you do not
make the child class, it cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be
accessed from within the class, outside the class, within the package, and
outside the package.

Understanding Static variables and methods


Static Variable:
 Static variable are also known as Class variables.
 These variables are declared similarly as instance variable, the difference
is that static variables are declared using the static keyword within a
class outside any method constructor or block.
 Unlike instance variable, we can only have one copy of a static variable
per class irrespective of how many objects were create.
 Static variables are created at the start of program execution and
destroyed automatically when execution ends.
 Initialization of Static Variable is not Mandatory. Its default value is
zero.
Static Methods:
 Static methods are methods that do not operate on objects. A Static
methods acts related to class declare a static method by using the static
keyword as a modifier.
 To declare a method as static is as follows:
Static return_type methodname(parameter)
{
//body of the method
}
 A method declared static has several restrictions:
1. They can only call the other static method.
2. They must only access static data.
3. They cannot refer to this in any other way.

Understanding Final variables and methods


Final Variable: Once we declare a variable with the final keyword, we can’t change
its value again. If we attempt to change the value of the final variable, then we will
get a compilation error. Generally, we can consider a final variable as a constant, as
the final variable acts like a constant whose values cannot be changed.
Initializing Final Variable: Normally, we set a value when declaring a final variable.
But if we don't, it's called a "blank final variable.“
Initializing a Blank Final Variable:To initialize a blank final variable, we have two
options:
Inside a constructor or an instance-initializer block (if the variable is not static).
Inside a static block (if the variable is static).
Multiple Constructors:If a class has multiple constructors, you must initialize blank
final variables in each constructor to avoid errors.

Final Method:As earlier, we discussed the Final Keyword and How to declare the
Final Variable. We can declare Java methods as Final Method by adding the Final
keyword before the method name. The Method with Final Keyword cannot be
overridden in the subclasses. The purpose of the Final Method is to declare methods
of how’s definition can not be changed by a child or subclass that extends it.
Purpose of Final Methods:
 Final methods are used to restrict the modification of a method's behavior
when a class is extended (subclassed).
 Final methods prevent subclasses from changing the way a method works
when they override it.
 By marking a method as final, you ensure that it always performs its
intended function, even in subclasses.
Marking methods as final helps maintain the integrity and consistency of method
behavior across subclasses.

Static Access
Final Access Modifier Modifier

This modifier is applicable to both outer


This modifier is only applicable to inner
and inner classes, variables, methods,
classes, methods, and variables.
and blocks.

It is not necessary to initialize the final It is necessary to initialize the static


variable at the time of its declaration. variable at the time of its declaration.

Final variable cannot be reinitialized. Static variables can be reinitialized.

Static methods can only access the static


Final method cannot be inherited. members of the class and can only be
called by other static methods.

Final access modifier does not allow Static access modifier allow the use of
the use of OOP concepts like OOP concepts within static blocks of
Inheritance and polymorphism. code.

Working with Nested Class


 Nested Class: Nested classes, also known as inner classes, are classes defined
within other classes. They allow you to logically group classes and improve
code organization.
 Types of Nested Classes:
There are four types of nested classes in Java:
 Static Nested Classes
 Inner Classes
 Local Classes
 Anonymous Classes.
 Benefits of Nested Classes:
 Improved encapsulation and code organization.
 Enhanced readability by grouping related classes.
 Better control of access to class members.
 Use Cases:
 Use static nested classes for utility functions.
 Use inner classes for modeling complex relationships.
 Use local and anonymous classes for short-term tasks.

Understanding Inner Class


 Inner Class: Inner classes, also known as nested classes, are classes
defined within other classes. They enable a more organized and
encapsulated code structure. Java supports four types of inner classes:
Member Inner Classes, Static Nested Classes, Local Classes,Anonymous
Classes.
 Syntax
public class Outer {

public class Inner {


// ...
}
}
 Member Inner Classes: Defined within an instance of the outer class. Can
access outer class members. Often used for logically grouping related
functionality.
 Static Nested Classes: Defined as static members of the outer class.
Frequently used for utility classes.
Example:
public class Enclosing {

private static int x = 1;

public static class StaticNested {


private void run() {
// method implementation
}
}
@Test
public void test() {
Enclosing.StaticNested nested = new Enclosing.StaticNested();
nested.run();
}
}
 Local Classes: Defined within a method or block of code. Access local
variables and parameters of the enclosing scope. Useful for small, self-
contained tasks.
 Anonymous Classes:Defined without a class name. Used for
implementing interfaces or extending classes on the fly. Handy for one-
time use.
Example:
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println("nice fruits");}
};
p.eat();
} }

 Advantages of Inner Classes:


• Improved encapsulation by restricting access to related
components.
• Enhanced code organization and readability.
• Effective for reducing code redundancy.
 Use Cases:
• Member inner classes: Model complex relationships.
• Static nested classes: Group utility functions.
• Local and anonymous classes: Short-term, specialized tasks

Introduction to String Class and String Buffer Class


String Class:
 In Java, the `String` class is used to represent sequences of characters,
such as words or text. It's a fundamental and widely used class in Java
for working with textual data.
 Strings in Java are immutable, meaning their values cannot be changed
once they are created.
 Strings can be created in Java using double quotes. You can also create
strings using the `new` keyword, but it's less common.
 Java provides a rich set of methods to manipulate and work with strings,
such as `concatenation`, `substring`, `length`, `indexOf`, and more.
 Java offers libraries like `StringBuilder` and `StringBuffer` for efficient
string manipulation when you need mutable strings.
 Strings are used extensively for text processing, user input, file
operations, and more.
 They are central to building user interfaces, web applications, and data
processing systems.
 Use `StringBuilder` or `StringBuffer` for frequent string modifications to
improve performance.
 Be mindful of memory usage when working with large strings.
Working with String Handling Methods
String Handling in Java:
1. Strings in Java:
- Text is represented as strings in Java.
- Java offers useful methods for string manipulation.
2. Common String Methods:
- `length()`: Get string length.
- `charAt(index)`: Get a character at a position.

- `substring(begin, end)`: Extract part of a string.


- `concat(str)`: Join strings.
- `equals(str)`: Compare strings.
- `toUpperCase()` and `toLowerCase()`: Change case.
- `split(delimiter)`: Split strings.
3. **String Concatenation**
- Combine strings using `+` or `concat()`.
4. **String Formatting**
- Create formatted strings with `String.format()`.
5. **Efficient Manipulation**
- Use `StringBuilder` or `StringBuffer` for frequent changes

6. **Regular Expressions**
- Advanced string matching with regex.

7. **Use Cases**
- Vital for text processing, user input, data handling.

8. **Best Practices**
- Opt for `StringBuilder` for efficient edits.
- Prefer `equals()` for comparisons.

9. **Summary**
- Java's string methods empower text handling in applications.

Command Line arguments


 Command-line arguments in Java are used to pass arguments to the main
program. Here are some key points about command-line arguments:
 Input for the Program: Command-line arguments are passed at runtime to the
Java program and are used as input.
 Received in the Main Method: The arguments passed from the console can be
received in the Java program’s main method.
 String Array: The command-line arguments are provided to the main function
as a string array argument.
 Any Number of Arguments: You can pass any number of arguments from the
command prompt.

You might also like