0% found this document useful (0 votes)
13 views25 pages

Class, Objects and Methods

class,obj

Uploaded by

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

Class, Objects and Methods

class,obj

Uploaded by

Arunprakash
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Class, Objects and

Methods
• Java is an object-oriented programming
language.

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

• A Class is like an object constructor, or a


"blueprint" for creating objects.
Create an Object and Class

Single Objects

public class Main { public class Main {


int x = 5; int x = 5;

public static void main(String[] args) { public static void main(String[] args) {
Main myObj = new Main(); Main myObj1 = new Main(); // Object 1
System.out.println(myObj.x); Main myObj2 = new Main(); // Object 2
} System.out.println(myObj1.x);
} System.out.println(myObj2.x);
}
}
public class Calculator {
// Method to perform addition
void add(int a, int b) {
int result = a + b;
System.out.println("Sum: " + result);
}

public static void main(String[] args) {


// Create object of the class
Calculator calc = new Calculator();

// Call the method using the object


calc.add(10, 20);
}
}
class Student { // Main class to run the program
// Data members (fields) public class Main {
int rollNumber; public static void main(String[] args) {
String name; // Create an object of Student
int age; Student s1 = new Student();

// Method to display student details // Assign values to the object's fields


void displayDetails() { s1.rollNumber = 101;
System.out.println("Roll Number: " + s1.name = "Arun";
rollNumber); s1.age = 20;
System.out.println("Name: " +
name); // Call method to display details
System.out.println("Age: " + age); s1.displayDetails();
} }
} }
Java Class Methods

public class Main {


static void myMethod() {
System.out.println("Hello World!");
}
}

Inside main, call myMethod():

public class Main {


static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {


myMethod();
}
}
Static vs
Public
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}

// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}

// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error

Main myObj = new Main(); // Create an object of Main


myObj.myPublicMethod(); // Call the public method on the object
}
} we created a static method, which means that it can be accessed without creating an object of
the class, unlike public, which can only be accessed by objects:
Access Methods With an Object

// Create a Main class


public class Main {

// Create a fullThrottle() method


public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}

// Create a speed() method and add a parameter


public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}

// Inside main, call the methods on the myCar object


public static void main(String[] args) {
Main myCar = new Main(); // Create a myCar object
myCar.fullThrottle(); // Call the fullThrottle() method
myCar.speed(200); // Call the speed() method
}
}
Java Constructors

• A constructor in Java is a special method that is used to


initialize objects.

• The constructor is called when an object of a class is


created.

• It can be used to set initial values for object attributes:

• constructor name must match the class name, and it cannot


have a return type (like void).

Types of Constructors in Java

• Default Constructor
• Parameterized Constructor
• Copy Constructor
Default Constructor

class simple{

// Default Constructor
simple() {
System.out.println("Default constructor");

public static void main(String[] args)


{
simple h = new simple();
}
}
Parameterized Constructor
class student {
String name;
int id;

student(String name, int id)


{
this.name = name;
this.id = id;
}
}

class stud
{
public static void main(String[] args)
{
student g = new student("Sweta", 68);
System.out.println(“StudentName: " + g1.name
+ " and StudentId: " + g1.id);
}
}
Copy Constructor in Java
copy constructor is passed with another object which copies the data available from the passed object to
the newly created object.

class CCJ {
class stud { public static void main(String[] args)
{
String name; // This would invoke the parameterized constructor
int id; System.out.println("First Object");
stud g1 = new g1("Sweta", 68);
stud(String name, int id) System.out.println(“StudentName: " + g1.name
{ + " and studentId: " + g1.id);
this.name = name; System.out.println();
this.id = id;
} // This would invoke the copy constructor
stud(stud obj2) stud g2 = new stud(g2);
{ System.out.println("Copy Constructor used Second Object");
this.name = obj2.name; System.out.println(“StudentName: " + g2.name + " and StudentId: "
this.id = obj2.id; + g2.id);
} }
} }
To create multiple constructors in the same class with
Constructor Overloading different parameter lists.
// Constructor with one argument but with
class stud { different
// type than previous
// constructor with one argument stud(long id)
stud(String name) {
{ System.out.println(
System.out.println("Constructor with one " "Constructor with one argument: "
+ "argument - String: " + name); + "Long: " + id);
} }
}
// constructor with two arguments
stud(String name, int age) class GFG {
{ public static void main(String[] args)
System.out.println( {
"Constructor with two arguments: " stud g2 = new stud("Sweta");
+ " String and Integer: " + name + " " +
stud g3 = new stud("Amiya", 28);
age);
}
stud g4 = new stud(325614567);
}
}
To create multiple constructors in the same class with
Constructor Overloading different parameter lists.
stud(long id)
{
System.out.println(
class stud { "Constructor with one argument: "
+ "Long: " + id);
// constructor with one argument }
stud(String name) //different method
{ void stud1(String m)
System.out.println("Constructor with one " {
+ "argument - String: " + name); System.out.println("Constructor with one "
} + "argument - String: " + m);
}
// constructor with two arguments }
stud(String name, int age) class GFG {
{ public static void main(String[] args)
System.out.println( {
"Constructor with two arguments: " stud g2 = new stud("Sweta");
+ " String and Integer: " + name + " " + g2.stud1("harini");//different parameter value
age); stud g3 = new stud("Amiya", 28);
}
stud g4 = new stud(325614567);
} }
this keyword class Student {
String name;
int age;

Student(String name,int a) {
this.name = name; ;// 'this.name' refers to instance variable, 'name' is constructor param
age=a;
}
void display()
{
System.out.println("Name: " + name);
System.out.println("Age="+age);
}
}
class Main
{
public static void main(String arg[])
{
Student s=new Student("hari",34);
s.display();
}
Recursion in Java Recursion is a process in which a function calls itself directly or indirectly is called recursion and
the corresponding function is called a recursive function.

// Java Program to implement


// Factorial using recursion // Driver Class
class GFG { class Recursion {

// recursive method // Main function


int fact(int n) public static void main(String[] args)
{ {
int result; GFG f = new GFG();

if (n == 1) System.out.println("Factorial of 3 is " + f.fact(3));


return 1; System.out.println("Factorial of 4 is " + f.fact(4));
result = fact(n - 1) * n; System.out.println("Factorial of 5 is " + f.fact(5));
return result; }
} }
}
Strings in Java
• In Java, the String class is part of the java.lang package and is used to represent a sequence of
characters.

• Strings in Java are immutable, meaning once a String object is created, it cannot be changed.

Using string literal:

String s = "hello";

Using new keyword:

String s = new String("hello");


Commonly Used String Methods:

Method Description
length() Returns the length of the string
charAt(int index) Returns character at a given index
substring(int start, int end) Returns part of the string
equals(String another) Compares two strings
equalsIgnoreCase(String another) Case-insensitive comparison
compareTo(String another) Lexicographically compares
toLowerCase() / toUpperCase() Converts to lower/upper case
trim() Removes leading and trailing spaces
concat(String s) Appends one string to another
replace(char old, char new) Replaces characters
Creating and Printing a String

public class StringExample1 {


public static void main(String[] args) {
String s1 = "Welcome";
String s2 = new String("Java");

System.out.println("s1: " + s1);


System.out.println("s2: " + s2);
} Output:
} s1: Welcome
s2: Java
Using Common String Methods

public class Strmethods{


public static void main(String[] args) {
String str = " Hello Java ";
System.out.println("Original: '" + str + "'");
System.out.println("Trimmed: '" + str.trim() + "'");
System.out.println("Length: " + str.length());
System.out.println("Uppercase: " +str.toUpperCase());
System.out.println("Lowercase: " + str.toLowerCase());
System.out.println("Substring (1,5): " + str.substring(1, 5));
System.out.println("Char at index 6: " + str.charAt(6));
}
}
Comparing Strings

public class StringEqualsExample {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "Hello";
String str3 = "hello";

System.out.println("str1 equals str2: " + str1.equals(str2)); // true


System.out.println("str1 equals str3: " + str1.equals(str3)); // false (due to case
difference)
}
}
Concatenation and Replace

public class StringConcatReplace {


public static void main(String[] args) {
String str = "Java is fun";

String result = str.concat(" and powerful");


String replaced = str.replace('a', '*');

System.out.println("Concatenated: " + result);


System.out.println("Replaced: " + replaced);
}
Splitting a String
public class StringSplit {
public static void main(String[] args) {
String data = "apple,banana,grape";

String[] fruits = data.split(",");

for (String fruit : fruits) {


System.out.println(fruit);
}
}
}
Garbage Collection in Java
Garbage Collection (GC) in Java is the process by which JVM (Java Virtual Machine) automatically
removes unused or unreachable objects from memory to free up space and avoid memory leaks.

Why Garbage Collection?

• Java developers don’t need to manually


deallocate memory (unlike C/C++).
• Helps prevent memory leaks and
OutOfMemoryError.
• Improves program performance and memory
usage.
public class GarbageExample {
public static void main(String[] args) {
GarbageExample g1 = new GarbageExample();
GarbageExample g2 = new GarbageExample();

// Now g1 and g2 refer to two different objects

g1 = null; // g1 is now eligible for garbage collection


g2 = null; // g2 is also eligible

// Request JVM to run Garbage Collector


System.gc();

System.out.println("End of main method.");


}

// This method is called just before the object is garbage collected


protected void finalize() {
System.out.println("Garbage collector is called. Object is deleted.");
}
}

You might also like