0% found this document useful (0 votes)
16 views

Unit-3 Java as Object Oriented Programming Language-Overview

The document provides an overview of Java as an object-oriented programming language, detailing its fundamentals, including arrays, string handling, and class methods. It discusses the different editions of Java, types of applications, and the Java platform, emphasizing its features such as simplicity, security, and platform independence. Additionally, it covers the creation and manipulation of one-dimensional and two-dimensional arrays in Java, including examples of declaration, instantiation, and initialization.

Uploaded by

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

Unit-3 Java as Object Oriented Programming Language-Overview

The document provides an overview of Java as an object-oriented programming language, detailing its fundamentals, including arrays, string handling, and class methods. It discusses the different editions of Java, types of applications, and the Java platform, emphasizing its features such as simplicity, security, and platform independence. Additionally, it covers the creation and manipulation of one-dimensional and two-dimensional arrays in Java, including examples of declaration, instantiation, and initialization.

Uploaded by

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

Sinhgad College of Engineering

Vadgaon Bk. Pune


Approved by AICTE New Delhi Recognized by Govt. of Maharashtra
Affiliated to Savitribai Phule Pune University
Accredited by NAAC with A+ Grade

Subject:- 210255: Principles of Programming Languages


Unit-3 Java as Object Oriented Programming Language-Overview

Mr. AJIT M. KARANJKAR


Assistant. Professor.
Department of Computer Engineering,
Sinhgad College of Engineering Vadgaon Bk, Pune-041
Email:- [email protected]

09-04-2025 1
Contents:
• Fundamentals of JAVA, Arrays: one dimensional array, multi-
dimensional array, alternative array declaration statements,
• String Handling: String class methods, Classes and Methods: class
fundamentals, declaring objects, assigning object reference variables, adding
methods to a class, returning a value, constructors, this keyword, garbage
collection, finalize() method, overloading methods, argument passing, object
as parameter, returning objects, access control, static, final, nested and inner
classes, command line arguments, variable - length arguments.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 2
Department Of Computer Engineering
UNIT-3
JAVA AS OBJECT ORIENTED
PROGRAMMING LANGUAGE-OVERVIEW

UNIT-II Structuring The data, Computation and Program


23-03-2023 3
Department Of Computer Engineering
3.1 FUNDAMENTALS OF JAVA ARRAY
3.1.1 One Dimensional Array
3.1.2 Multidimensional Array
3.1.3 Alternative Declarations Statements.

4
3.1 Fundamentals of Java
❑ What is Java?
• Java is a high-level, general-purpose, object-oriented, and secure programming language
developed by James Gosling at Sun Microsystems, Inc. in 1991.

• It is formally known as OAK. In 1995, Sun Microsystem changed the name to Java. In
2009, Sun Microsystem takeover by Oracle Corporation.
❑ Editions of Java:
Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the server
and manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices such as set-
top boxes, phone, and appliances.
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 5
Department Of Computer Engineering
3.1 Fundamentals of Java
❑ Types of Java Applications
There are four types of Java applications that can be created using Java programming:
• Standalone Applications: Java standalone applications uses GUI components such as
AWT, Swing, and JavaFX. These components contain buttons, list, menu, scroll panel,
etc. It is also known as desktop alienations.
• Enterprise Applications: An application which is distributed in nature is called
enterprise applications.

• Web Applications: An applications that run on the server is called web applications.
We use JSP, Servlet, Spring, and Hibernate technologies for creating web applications.

• Mobile Applications: Java ME is a cross-platform to develop mobile applications


which run across smartphones. Java is a platform for App Development in Android.
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 6
Department Of Computer Engineering
3.1 Fundamentals of Java
❑ Java Platform

• Java Platform is a collection of programs. It helps to develop and run a program written
in the Java programming language.

• Java Platform includes an execution engine, a compiler and set of libraries. Java is a
platform-independent language.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 7
Department Of Computer Engineering
3.1 Fundamentals of Java
❑ Feature of Java

• Simple: Java is a simple language because its syntax is simple, clean, and easy to
understand.

• Object-Oriented: In Java, everything is in the form of the object. It means it has some
data and behavior. A program must have at least one class and object.

• Secure: Java is a secure programming language because it has no explicit pointer and
programs runs in the virtual machine. Java contains a security manager that defines the
access of Java classes.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 8
Department Of Computer Engineering
3.1 Fundamentals of Java
• Platform-Independent: Java provides a guarantee that code writes once and run
anywhere. This byte code is platform-independent and can be run on any machine.

• Java can be compiled and interpreted: Normally programming languages can be


either compiled or interpreter but java is language which can be compiled as well as
interpreted . First java compiler translates the java source program into a special code
called bytecode. Then java interpreter this bytecode to obtain the equivalent machine
code. The machine code is then directly executed to obtain the output.

• High Performance: Java is an interpreted language. Java enables high performance


with the use of the Just-In-Time compiler.
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 9
Department Of Computer Engineering
3.1 Fundamentals of Java

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 10
Department Of Computer Engineering
3.1 Fundamentals of Java

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 11
Department Of Computer Engineering
3.1 Fundamentals of Java
• How to Write a Java Program?
• Write a program on the notepad and save it with .java (for example, DemoFile.java)
extension.

class DemoFile
{
public static void main(String args[])
{
System.out.println("Hello!");
System.out.println("Java");
}
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 12
Department Of Computer Engineering
3.1 Fundamentals of Java
• Step 2:
Open Command Prompt.
Step 3:
Set the directory in which the .java file is saved. In our case, the .java file is saved in
C:\\demo.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 13
Department Of Computer Engineering
3.1 Fundamentals of Java
Step 4:
• Use the following command to compile the Java program. It generates a .class file in the
same folder. It also shows an error if any.

javac DemoFile.java
Use the following command to run the Java program:
java DemoFile

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 14
Department Of Computer Engineering
3.1.1 Array
• An array is a container object that holds a fixed number of values of a single type.
• The length of an array is established when the array is created.
• After creation, its length is fixed.
• You have seen an example of arrays already, in the main method of the "Hello World!"
application.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 15
Department Of Computer Engineering
3.1.1 One Dimensional Array

• A one-dimensional array in Java is a collection of similar types of elements stored


at contiguous memory locations.

• Arrays can be one-dimensional or multi-dimensional. One dimensional arrays can store


multiple values of the same primitive type such as int, float, long, String, etc. or objects
of the same class.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 16
Department Of Computer Engineering
3.1.1 One Dimensional Array
Creating a one-dimension array in Java
• A one-dimensional array can be visualized as a single row or a column of array elements
that are represented by a variable name and whose elements are accessed by index
values.

• For example, the score of a series of football matches can be stored in a one-dimensional
array.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 17
Department Of Computer Engineering
3.1.1 One Dimensional Array
• data-type: The data type determines the data type of each element present in the array-
like char, int, float, objects etc.
• var-name: It is the name of the reference variable which points to the array object
stored in the heap memory.
• Example:

int Array[];

long longArray[];

float floatArray[];

double doubleArray[];

char charArray[];
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 18
Department Of Computer Engineering
3.1.1 One Dimensional Array
Construction of one-dimensional array in Java
• There are mainly two ways to create an array in java :
• We can declare and store the values directly at the time of declaration :
• int marks[ ] = { 90, 97, 95, 99, 100 };
• JVM(Java Virtual Machine that drives the Java Code, converts
Java bytecode into machine language) will
assign five contiguous memory locations to
store the values assigned to the array.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 19
Department Of Computer Engineering
3.1.1 One Dimensional Array
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
} UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 20
Department Of Computer Engineering
3.1.1 One Dimensional Array
Output:
10
20
70
40
50

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 21
Department Of Computer Engineering
3.1.1 One Dimensional Array
Declaration, Instantiation and Initialization of Java Array:
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization

Example:
//Java Program to illustrate the use of declaration, instantiation and initialization of Java array
in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization //printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 22
Department Of Computer Engineering
3.1.1 One Dimensional Array
Output:
33
3
4
5

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 23
Department Of Computer Engineering
3.1.2 Two Dimensional Array
• Two Dimensional Array Declaration in Java

• Since a 2D array consists of rows and columns, we need two indices, one to refer rows
and the other to a particular column in that row.

• Syntax:

• DataType[][] ArrayName;

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 24
Department Of Computer Engineering
3.1.2 Two Dimensional Array
• Create Two Dimensional Array in Java

• Hence, to create a two-dimensional array object we need to use the new keyword as
shown below:
• Syntax
• // Declaring 2D array
DataType[][] ArrayName;

• // Creating a 2D array
ArrayName = new DataType[r][c];

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 25
Department Of Computer Engineering
3.1.2 Two Dimensional Array
• Here, the new DataType [r][c] statement creates a two dimensional array object that
contains r rows and c columns and elements of DataType type.

• This array object is referenced by the reference variable ArrayName.

• Let's understand the creation of Java's two-dimensional array with an example:

• //Declaring 2D array
int[ ][ ] a;

• //Creating a 2D array
a = new int[3][3];
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 26
Department Of Computer Engineering
3.1.2 Two Dimensional Array
• Java Two Dimensional Array of Primitive Type
Arrays are a collection of elements that have similar data types. Hence, we can create an
array of primitive data types as well as objects.

• int[][] AIntegerArray; // 2D Integer Array


• byte[][] AByteArray; // 2D Byte Array
• short[][] AShortArray; // 2D Short Array
• long[][] ALongArray; // 2D Long Array
• float[][] AFloatArray; // 2D Float Array
• double[][] ADoubleArray; // 2D Double Array
• boolean[][] ABooleanArray; // 2D Boolean Array
• char[][] ACharArray; // 2D Character Array
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 27
Department Of Computer Engineering
3.1.2 Two Dimensional Array
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in Java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
23-03-2023
UNIT-III Java as Object Oriented Programming Language-Overview
Department Of Computer Engineering
28
3.1.2 Two Dimensional Array
• Example of Multidimensional Java Array
//Java Program to illustrate the use of multidimensional array
class Testarray3 {
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}} 23-03-2023 UNIT-III Java as Object Oriented Programming Language-Overview
29
Department Of Computer Engineering
3.1.2 Two Dimensional Array
Output:
123
245
445

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 30
Department Of Computer Engineering
3.1.3 Alternative Array Declaration Statement:
• For example, the following two declarations are equivalent:

int al[] = new int[3];


int[ ] a2 = new int[3];

• The following declarations are also equivalent:

char t1[][] = new char[3][4];


char[][] t2 = new char[3][4];

• This alternative declaration form offers convenience when declaring several arrays
at the same time:

int[ ] nums, nums2, nums3; // create three arrays


UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 31
Department Of Computer Engineering
3.1.3 Alternative Array Declaration Statement:
• The square brackets follow the type specifier, and not the name of the array variable.
type[] var-name;

• For example, the following two declarations are equivalent:


int al[] = new int[3];
int[] a2 = new int[3];

• The following declarations are also equivalent:

char d1[][] = new char[3][4];


char[][] d2 = new char[3][4];

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 32
Department Of Computer Engineering
3.2 String Handling
3.2.1 Finding Length of String
3.2.2 Concatenation.
3.2.3 String Comparison.
3.2.4 Searching for the Substring.
3.2.5 Replace Character from the string.
3.2.6 Upper Case & Lower Case.

33
3.2 String Handling:
• In Java, string is basically an object that represents sequence of char values.

• An array of characters works same as Java string.


For example:

char[] ch={‘w’,’e’,’l’,’c’,’o’,’m’,’e’};
String s=new String(ch);
is same as:

String s=“welcome";

• Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 34
Department Of Computer Engineering
3.2 String Handling:
• String Example:
public class StringExample{
public static void main(String args[])
{
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
} UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 35
Department Of Computer Engineering
3.2 String Handling:
• Output:

java
strings
example

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 36
Department Of Computer Engineering
3.2.1 Finding Length of String:
Java String length()
• The Java String class length() method finds the length of a string.

• The length of the Java string is the same as the Unicode code units of the string.
Java String length() method example
Example:
public class strlen
{
public static void main(String args[])
{
String s1="javatpoint";
String s2="python";
System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string
System.out.println("string length is: "+s2.length());//6 is the length of python string
}
}
Output:
string length is: 10
string length is: 6
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 37
Department Of Computer Engineering
3.2.2 String Concatanation
• In Java, String concatenation forms a new String that is the combination of multiple strings.
There are two ways to concatenate strings in Java:

• By + (String concatenation) operator

• By concat() method

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 38
Department Of Computer Engineering
3.2.2 String Concatanation
1) String Concatenation by + (String concatenation) operator Java String concatenation
operator (+) is used to add strings. For Example:
Example:
class TestStringConcatenation1
{
public static void main(String args[])
{
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Output: Sachin Tendulkar
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 39
Department Of Computer Engineering
3.2.2 String Concatenation:
2) String Concatenation by concat() method
The String concat() method concatenates the specified string to the end of current string.
Example:
public String concat(String another) Output: Sachin Tendulkar
class TestStringConcatenation3
{
public static void main(String args[])
{
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
} 23-03-2023
} UNIT-III Java as Object Oriented Programming Language-Overview
Department Of Computer Engineering
40
3.2.3 String Substring:
• String substring(): This method has two variants and returns a new string that is a substring of
this string.
• The substring begins with the character at the specified index and extends to the end of this string.
Endindex of substring starts from 1 and not from 0.
Example:
public class Substr2 {
public static void main(String args[])
{ // Initializing String
String Str = new String("Welcome to geeksforgeeks");
// using substring() to extract substring
// returns geeks
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(10, 16));
}
}
Output: geeks
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 41
Department Of Computer Engineering
3.2.4 String Comparison:
We can compare String in Java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo()
method), reference matching (by == operator) etc.
There are three ways to compare String in Java:
1. By Using equals() Method
2. By Using == Operator
3. By compareTo() Method

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 42
Department Of Computer Engineering
3.2.4 String Comparison:
1) By Using equals() Method
The String class equals() method compares the original content of the string. It compares values of
string for equality. String class provides the following two methods:
Example:
public class strcmp
{
public static void main(String[] args)
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Sumit";
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s4));
}
}
Output:
True
True
False UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 43
Department Of Computer Engineering
3.2.4 String Comparison:
2) By Using == operator:
The == operator compares references not values.
Example:
public class str2cmp
{
public static void main(String[] args)
{
String s1="Sumit";
String s2="Sumit";
String s3="Amit";
System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s2==s3);
}
Output:
True
False
False
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 44
Department Of Computer Engineering
3.2.5 Replace Character from String:
• The Java String class replace() method returns a string replacing all the old char or
CharSequence to new char or CharSequence.

• The replace() method searches a string for a specified character, and returns a new string
where the specified character(s) are replaced.

• Syntax:
• public String replace(char searchChar, char newChar)

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 45
Department Of Computer Engineering
3.2.5 Replace Character from String:
Example:
public class replace {
public static void main(String[] args)
{
String s1="Welcome Student's";
String replcestr=s1.replace('e','a');
System.out.println("First String:"+s1);
System.out.println("Replace String:"+replcestr);
}
}
Output:
First String: Welcome Student’s
Replace String: Walcoma Studant’s

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 46
Department Of Computer Engineering
3.2.6 Upper Case & Lower Case :
The toLowerCase() method converts a string to lower case letters.
The toUpperCase() method converts a string to Upper case letters.
Syntax
public String toLowerCase( )
public String toUpperCase( )
Example:
public class uplow {
public static void main(String[] args)
{
String s1="Hello Students";
System.out.println(“String LowerCase:”+s1.toLowerCase());
System.out.println(“String UpperCase:”+s1.toUpperCase());
}
}
Output:
String LowerCase: hello students
String UpperCase:HELLO STUDENTS

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 47
Department Of Computer Engineering
3.3 Class & Methods
• Java Classes
• 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.
• Example:
class customer{
int id;
int age;
String name;
-----
---
public void display(){
} 23-03-2023
UNIT-III Java as Object Oriented Programming Language-Overview
48
Department Of Computer Engineering
3.3 Class & Methods
Syntax to declare a class:
class <class_name>{
field;
method;
}

• Instance variable in Java


• A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time.

• It gets memory at runtime when an object or instance is created. That is why it is known as
an instance variable.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 49
Department Of Computer Engineering
3.3 Class & Methods
There are two types of methods in Java:
• Predefined Method
• User-defined Method

• Predefined Method:
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods.

It is also known as the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point.
• User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 50
Department Of Computer Engineering
3.3 Class & Methods
• Addition.java
public class Addition
{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b); //a and b are actual parameters
System.out.println("The sum of a and b is= " + c);
}

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 51
Department Of Computer Engineering
3.3 Class & Methods
//user defined method
public static int add(int n1, int n2) //n1 and n2 are formal parameters
{
int s;
s=n1+n2;
return s; //returning the sum
}
}
• Output:
C:\>javac Adition.java
C:\>java Addition
The Sum of a and b is= 24
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 52
Department Of Computer Engineering
3.4 Objects
• Objects are nothing but the instances of the class . Hence the block of memory gets
allocated for these instance variable.

• In Java, an object is created from a class. We have already created the class named Main,
so now we can use this to create objects.

• To create an object of Main, specify the class name, followed by the object name, and use
the keyword new:

• Example:
Sample myObj = new Sample();

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 53
Department Of Computer Engineering
3.4 Objects
class Sample {
int x = 5;

public static void main(String[] args) {


Sample myObj = new Sample();
System.out.println(myObj.x);
}
}
Output:
c:\>javac Adition.java
c:\>java Addition
5
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 54
Department Of Computer Engineering
3.5 Adding Method to Class.
Methods are nothing but the functions defined by the particular class.
Syntax:
class classname
{
declarations of member variables;
definitions of method
{
----
----
}
}

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 55
Department Of Computer Engineering
3.5 Adding Method to Class.
How to add method to a class ?

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 56
Department Of Computer Engineering
3.5 Adding Method to Class.
import java.io.*;
import java.lang;
import java.math;
public class Student
{
String name;
int roll;
double marks;
public void display(String n, int r, double m)// member function defined here
{
System.out.println("Name:"+n);
System.out.println("Roll Number:"+r);
System.out.println("Marks:"+m);
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 57
Department Of Computer Engineering
3.5 Adding Method to Class.
public static void main(String args[])
{
int a,b;
Student obj=new Student();
obj.display("Amit",15,78.55);
}
Output:
c:\>javac Student.java
c:\>java Student
Name:Amit
Roll Number:15
Marks:78.55
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 58
Department Of Computer Engineering
3.6 returning a Value
• A return statement causes the program control to transfer back to the caller of a method

• A return type may be a primitive type like int, float, double, a reference
type or void type(returns nothing).

• The syntax of a return statement is the return keyword is followed by the value to be
returned.

• Syntax:
return returnvalue;

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 59
Department Of Computer Engineering
3.6 returning a Value
• Programming Example:
public class ReturnTypeTest1
{
public int add() { // without arguments
int x = 30;
int y = 70;
int z = x+y;
return z;
}
public static void main(String args[])
{
ReturnTypeTest1 test = new ReturnTypeTest1();
int add = test.add();
System.out.println("The sum of x and y is: " + add);
}
} Output: The sum of x and y is: 100 UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 60
Department Of Computer Engineering
3.7 Constructor
• In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created.

• At the time of calling constructor, memory for the object is allocated in the memory.

• It is a special type of method which is used to initialize the object.

• Every time an object is created using the new() keyword, at least one constructor is called.
Syntax:
class Employee //class name
{
Employee() //constructor
{
//body of constructor
}
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 61
Department Of Computer Engineering
3.7 Constructor
• In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created.

• At the time of calling constructor, memory for the object is allocated in the memory.

• It is a special type of method which is used to initialize the object.

• Every time an object is created using the new() keyword, at least one constructor is called default
constructor.
Syntax:
class Employee //class name
{
Employee() //constructor
{
//body of constructor
}
} 23-03-2023 UNIT-III Java as Object Oriented Programming Language-Overview
62
Department Of Computer Engineering
3.7 Constructor
• Types of Java constructors
There are two types of constructors in Java:
✓ Default constructor (no-arg constructor).
✓ Parameterized constructor.
✓ Copy Constructor.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 63
Department Of Computer Engineering
3.7 Constructor (Parameterized Constructor)
• Parameterized constructors in java are the programmer written constructors in a class
which have one or more than one arguments.

• Syntax:
public class Sample // Create a Class
{
int j;
sample(int i)// Parametrized Constructor
{
this.i = i;
}
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 64
Department Of Computer Engineering
3.7 Constructor (Parameterized Constructor)
Sample Program for Parameterized Constructor:
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);
}

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 65
Department Of Computer Engineering
3.7 Constructor (Parameterized Constructor)
public static void main(String args[])
{
//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
22223-03-2023
Aryan UNIT-III Java as Object Oriented Programming Language-Overview
66
Department Of Computer Engineering
3.7 Constructor (Default Constructor)
• A constructor is called "Default Constructor" when it doesn't have any parameter.
• The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
• Syntax:
public class Sample // Create a Class
{
int j;
sample()// Default Constructor
{
//Body of constructor
}
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 67
Department Of Computer Engineering
3.7 Constructor (Default Constructor)
Sample Program for Default Constructor:
class Student3{
int id;
String name;
Student3()
{ id=0;
name=“karan”;
}
void display() //method to display the value of id and name
{ System.out.println(id+" "+name);
}
public static void main(String args[]){
Student3 s1=new Student3(); //creating objects
Student3 s2=new Student3();
s1.display(); //displaying values of the object
s2.display();
}
}
Output:
0 karan
0 karan23-03-2023 UNIT-III Java as Object Oriented Programming Language-Overview
68
Department Of Computer Engineering
3.7 Constructor (Copy Constructor)
• In Java, a copy constructor is a special type of constructor that creates an object using
another object of the same Java class.
• It returns a duplicate copy of an existing object of the class.

• Syntax:
class_name (class_name ref) //Copy Constructor
{
//code
}

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 69
Department Of Computer Engineering
3.7 Constructor (Copy Constructor)
Sample Program for copy Constructor:
package Demo;
public class CopyConstr
{
String web;
CopyConstr (String w)
{ web = w;
}
/* This is the Copy Constructor, it copies the values of one object to the another object (the object
that invokes this constructor) */
CopyConstr (CopyConstr cc)
{
web = cc.web;
UNIT-III Java as Object Oriented Programming Language-Overview
} 23-03-2023 Department Of Computer Engineering
70
3.7 Constructor (Copy Constructor)
void disp ()
{
System.out.println ("Constructor: " + web);
}
public static void main (String args[])
{
CopyConstr obj1 =new CopyConstr ("Example of Copy Constructor in Java");
CopyConstr obj2 = new CopyConstr (obj1);
obj1.disp ();
obj2.disp ();
}
}
Output:
Example of Copy Constructor in Java
Example of Copy Constructor in Java

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 71
Department Of Computer Engineering
3.8 This Keyword
• There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

1) this: to refer current class instance variable


• The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 72
Department Of Computer Engineering
3.8 This Keyword
Understanding the problem without this keyword:
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{ rollno=rollno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 73
Department Of Computer Engineering
3.8 This Keyword
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000.0);
Student s2=new Student(112,"sumit",6000.0);
s1.display();
s2.display();
}
}
Output:
0 null 0.0
0 null 0.0

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 74
Department Of Computer Engineering
3.7 This Keyword
Understanding the problem with this keyword:
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{ this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 75
Department Of Computer Engineering
3.7 This Keyword
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000.0);
Student s2=new Student(112,"sumit",6000.0);
s1.display();
s2.display();
}
}
Output:
111 ankit 5000.0
112 sumit 6000.0

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 76
Department Of Computer Engineering
3.8 Garbage Collection
• Garbage collection in Java is the process by which Java programs perform automatic
memory management.

• Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for
short.

• In Java garbage means unreferenced objects.

• In processing reclaiming the runtime unused memory automatically. It is way to other destroy the
unused objects.

• To do so we are using free( ) function in c language. And delete( ) in c++ Language. But in java
performed automatically. So java provides better memory management.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 77
Department Of Computer Engineering
3.8 Garbage Collection
• In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects.

There are three basic steps in garbage collection:

• Mark: The garbage collector scans the heap memory segment and marks all the live
objects—that is, objects to which the application holds references. All the objects that have
no references to them are eligible for removal.

• Sweep: The garbage collector recycles all the unreferenced objects from the heap.

• Compact: The sweep step tends to leave many empty regions in heap memory, causing
memory fragmentation. Therefore, the compact phase helps arrange the objects into the
contiguous blocks at the start of the heap.
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 78
Department Of Computer Engineering
3.8.1 finalize( ) Method
• The finalize() method is invoked each time before the object is garbage collected. This
method can be used to perform cleanup processing. This method is defined in Object class
as:
protected void finalize()
{
}

• gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 79
Department Of Computer Engineering
3.8.1 finalize( ) Method
Simple Example of garbage collection in java
class GarbageEx1
{
public void finalize()
{ System.out.println("Garbage Collection");
}
public static void main(String args[])
{
GarbageEx1 obj1=new GarbageEx1();
GarbageEx1 obj2=new GarbageEx1();
obj1=null;
obj2=null;
System.gc();
}
} Output:
Garbage Collection
Garbage Collection
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 80
Department Of Computer Engineering
3.9 Overload Method
• If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

• Different ways to overload the method:


• There are two ways to overload the method in java

1) By changing number of arguments

2) By changing the data type

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 81
Department Of Computer Engineering
3.9 Overload Method
1) Method Overloading: changing no of arguments
class cal{
static int add(int a,int b)
{return a+b;
}
static int add(int a,int b,int c)
{return a+b+c;
}
} class Test1 extends cal
{ public static void main(String[] args)
{ Test1 t1=new Test1();
System.out.println(t1.add(11,11));
System.out.println(t1.add(11,11,11));
}}
Output: 22
23-03-2023
UNIT-III Java as Object Oriented Programming Language-Overview
82
Department Of Computer Engineering
3.9 Overload Method
2) Method Overloading: changing no of Data Types
class cal{
static int add(int a,int b)
{return a+b;
}
static double add(double a,double b)
{return a+b;
}}
class Test2 extends cal
{ public static void main(String[] args)
{ Test2 t1=new Test2();
System.out.println(t1.add(11,11));
System.out.println(t1.add(11.5,11.5));
}}
Output:23-03-2023
22 UNIT-III Java as Object Oriented Programming Language-Overview
83
Department Of Computer Engineering
3.10 Argument Passing
Parameter can be passed to the function by two ways –
1. Call by value
2. Call by Reference.

Call by value
• Call by Value means calling a method with a parameter as value. Through this, the
argument value is passed to the parameter.

Call by Reference:
• Java uses only call by value while passing reference variables as well. The parameter
passing by reference allows to change the values after the function call.
• But use of variables as a parameter does not allow to pass the parameter.

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 84
Department Of Computer Engineering
3.10 Argument Passing
//call by value in Java Program
public class value
{
static void display(int num)
{
num=num+05;
System.out.println(“Call by Value in Method:"+num);
}
public static void main(String[] args)
{
int num=10;
System.out.println(“Call by Value Before Method Call:"+num);
display(num);
System.out.println(“Call by Value After Method Call:"+num);
}
Output:
Call by Value Before Method Call:10
Call by Value in Method:15
Call by Value After Method Call:10
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 85
Department }Of Computer Engineering
3.10 Argument Passing
//call by Reference in Java Program
public class reference
{ int num=10;
static void display(reference r)
{ r.num=r.num+10;
System.out.println("Call By Reference in Method:"+r.num);
}
public static void main(String[] args)
{ reference ref=new reference();
System.out.println("Call By Reference Before Method Call:"+ref.num);
display(ref);
System.out.println("Call By Reference After Method Call:"+ref.num);
} UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 86
Department Of Computer Engineering
}
3.10 Argument Passing
Output:
Call By Reference Before Method Call:10
Call By Reference in Method:20
Call By Reference After Method Call:20

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 87
Department Of Computer Engineering
3.11 Object as a Parameter.
• A method can take an objects as a parameter. For example, in the following program, the
method setData( ) takes three parameter.

• The first parameter is an Data object. If you pass an object as an argument to a method, the
mechanism that applies is called pass-by-reference.

• Using Dot Operator the object value can be accessed.

• Syntax:
Data_type_name_of _method(object_name)
{
//body of method.
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 88
Department Of Computer Engineering
3.11 Object as a Parameter.
Example:
class objdemo
{
int height;
int width;
objdemo(int h,int w)
{
height=h;
width=w;
}

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 89
Department Of Computer Engineering
3.11 Object as a Parameter.
void area(objdemo o)
{ int result=(height+o.height,weight+o.weight);
System.out.println("The Area is"+result);
}}
class Demo
{ public static void main(String args[])
{ objdemo obj1=new objdemo(2,3);
objdemo obj2=new objdemo(10,20);
obj1.area(obj2);
}}
c:\test\javac objdemo.java
c:\test\java objdemo
The Area is 276 UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 90
Department Of Computer Engineering
3.12 Access Control
Example:
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class.

We can change the access level of fields, constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:


• Public
• Private
• Protected
• Default

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 91
Department Of Computer Engineering
3.12 Access Control
• Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.

• Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

• Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.

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

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 92
Department Of Computer Engineering
3.12 Access Control

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 93
Department Of Computer Engineering
3.12 Access Control
• Public: The public access modifier is accessible everywhere. It has the widest scope among
all other modifiers.
class A
{ public void msg() {
System.out.println("Hello Student \nHow are u?");
} }
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
} Output:
Hello Student
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 94
How are u? Department Of Computer Engineering
3.12 Access Control
• Private: The private access modifier is accessible only within the class.
class A
{ private int data=40;
private void msg()
{ System.out.println("Hello java");
}
}
public class Simple
{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 95
Department Of Computer Engineering
3.12 Access Control
obj.msg();//Compile Time Error
}
}
Output:
error: data has private access in A
System.out.println(obj.data);//Compile Time Error
error: msg() has private access in A
obj.msg();//Compile Time Error
^
2 errors

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 96
Department Of Computer Engineering
3.12 Access Control
class sample
{ private int data=40;
private void msg()
{ System.out.println("Hello Java");
}
public static void main(String args[])
{ sample s=new sample();
System.out.println(s.data);
s.msg();
}}
Output:
40
Hello Java UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 97
Department Of Computer Engineering
3.12 Access Control
• Protected
• The protected access modifier is accessible within package and outside the package but
through inheritance only.
• The protected access modifier can be applied on the data member, method and constructor.
• Example:
class A
{ protected void msg(){System.out.println("Hello");
} }
class B extends A {
public static void main(String args[]) {
B obj = new B();
obj.msg();
} } Output:
UNIT-III Java as Object Oriented Programming Language-Overview
Hello23-03-2023 Department Of Computer Engineering
98
3.12 Access Control
• Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package.

class A
{
void msg()
{
System.out.println("Try it");
}
}
//save by DefE1.java
class DefE1 extends A {
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 99
Department Of Computer Engineering
3.12 Access Control
void msg()
{ System.out.println("Try to access the overridden method");
}
public static void main(String[] args) {
DefE1 p=new DefE1();
p.msg();
}
}
Output:
Try to access the overridden method

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 100
Department Of Computer Engineering
3.13 Static Member
• The static members can be static data member or static method.
• The static keyword can be used with methods, fields, classes (inner/nested), blocks.
class staticA
{
static int j=10;
static void fun(int k)
{
System.out.println("J="+j);
System.out.println("K="+k);
}
};

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 101
Department Of Computer Engineering
3.13 Static Member
class staticB
{
public static void main(Strings args[])
{
System.out.println("J="+staticA.J);
staticA.fun(20);
}
} output:
J=10
K=20
J=10

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 102
Department Of Computer Engineering
3.14 Nested Inner Class:
• Java inner class or nested class is a class that is declared inside the class or interface.
• We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

• Syntax of Inner class


class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 103
Department Of Computer Engineering
3.15 Command Line Argument
• The java command-line argument is an argument i.e. passed at the time of running the
java program.
• Example:
class cmd1
{ public static void main(String args[])
{ System.out.println("Your first argument is: "+args[0]);
}
}
Output:
javac cmd1.java
javac cmd1 Hello
Your first argument is:Hello

UNIT-III Java as Object Oriented Programming Language-Overview


23-03-2023 104
Department Of Computer Engineering
3.16 Variable Length Argument
• Java Allows the method to use variable length arguments.

• The varrags allows the method to accept zero or muliple arguments

Syntax:
return_type method_name(data_type... variableName)
{ }
Example:
class Test1
{
public static void main(String args[])
{
System.out.println("Sum:"+display(20,30));
UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 105
Department Of Computer Engineering
System.out.println("Sum:"+display(20,30,40));
3.16 Variable Length Argument
System.out.println("Sum:"+display(10,20,30,40,50));
}
public static int display (int ... val)
{
int total=0;
for(int x:val)
total+=x;
return total;
}
}
Output:
Sum:50
Sum:90 UNIT-III Java as Object Oriented Programming Language-Overview
23-03-2023 106
Department Of Computer Engineering
Sum:150

You might also like