Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

_Unit 3 Java as Object Oriented Programming Language- Overview

Uploaded by

anaghasalunke44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

_Unit 3 Java as Object Oriented Programming Language- Overview

Uploaded by

anaghasalunke44
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 181

SNJB’s Late Sau. K. B. J.

College of Engineering

SE Computer- Division A
Course Name :Principles of Programming Language
Course Code: 210256
Course InCharge: Kainjan M. Sanghavi

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Unit 3
Java as Object Oriented Programming Language-Overview
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.
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Topic Book To Refer

Fundamentals of JAVA, Arrays: one dimensional Herbert Schildt, "The Complete Reference
Java", 9th Ed, TMH,ISBN: 978-0-07-
array, multi-dimensional array, alternative array
180856-9.
declaration statements ,String Handling: String class
methods Programming With Java, 3rd Edition, E.
Classes and Methods: class fundamentals, declaring
Balaguruswamy

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.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Topic Book To Refer

String Handling: String class methods Herbert Schildt, "The Complete Reference
Java", 9th Ed, TMH,ISBN: 978-0-07-
Classes and Methods: class fundamentals, declaring
180856-9.
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.

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Topic Book To Refer

String Handling: String class methods Herbert Schildt, "The Complete Reference
Java", 9th Ed, TMH,ISBN: 978-0-07-
180856-9.
Page No- 413-431

Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Introduction to JAVA Programming

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

What is Java?

Java is a programming language and a platform. Java is a high level,


robust, object-oriented and secure programming language.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
History of Java

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java. Before Java, its name was
Oak. Since Oak was already a registered company, so James Gosling and his team
changed the Oak name to Java.

Platform: Any hardware or software environment in which a program runs, is known


as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Java Version History

5 6 7 8 0 2 4 6 1
199 199 199 199 200 200 200 200 201 2014

JDK Alpha & Beta


Evolution

Java SE 6

Java SE 7

Java SE 8
J2SE 1.2

J2SE 1.3

J2SE 1.4

J2SE 5.0
JDK 1.0

JDK 1.1
Of Java SE 9
Java

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Features of Java

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Features of Java

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Simple
● It is free from pointer due to this execution time of application is improved.
[Whenever we write a Java program without pointers then internally it is
converted into the equivalent pointer program].
● It has Rich set of API (application protocol interface).
● It has Automatic Garbage Collector which is always used to collect un-
Referenced (unused) Memory location for improving performance of a Java
program.
● It contains user friendly syntax for developing any applications.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

JAVA Compiler and Interpreter

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java Life Cycle
Java Programs Normally Undergo Four Phases
Edit
Compile
Load
Programmer
Writes Compiler creates Execute
program Byte-codes from
program Class loader stores
Byte-codes in memory
Translate byte codes
Into machine language

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Object Oriented
● Since it is an object-oriented language, it will support the following features:
○ Class
○ Object
○ Encapsulation
○ Abstraction
○ Inheritance
○ Polymorphism

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Is Java Purely
Object Oriented?

Yes Then why?

No Then Why?

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Platform Independent

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

JVM, JDK ,JRE

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Difference between JDK, JRE and JVM
JDK JRE JVM
Java Development Kit Java Runtime Environment Java Virtual Machine
JVM is an abstract
JDK is an acronym JRE is used to machine. It is a
for Java Development provide runtime specification that
Kit. It physically environment. It is provides runtime
exists. It contains JRE the implementation environment in which
+ development tools. of JVM. It physically java bytecode can be
exists. executed.

JDK is a software development kit whereas JRE is a software bundle that allows Java program
to run, whereas JVM is an environment for executing bytecode.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Analogy to Explain JVM, JDK ,JRE

View

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Secure

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Secure

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Robust
● Capable of handling run-time errors,
● Supports automatic garbage collection
● Exception handling, and
● Avoids explicit pointer concept.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Architecture Neutral

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Architecture Interpreted

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Multithreading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Multithreading

● Multithreaded means handling multiple tasks


simultaneously or executing multiple portions (functions)
of the same program in parallel.
● The code of java is divided into smaller parts and Java
executes them in a sequential and timely manner.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Distributed

● Multiple programmers at many locations to work


together on a single project.
● Support RMI (Remote Method Invocation) and EJB (Enterprise
JavaBeans).

● Extensive library of classes for interacting, using TCP/IP


protocols such as HTTP and FTP, which makes creating
network connections much easier than in C/C++ .

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Distributed

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java is Dynamic

● Classes are not loaded all at once.


● They jump into action only when an invoke operation executes
or some data about the class is needed in the memory.
● Java finalizes invoking instructions during runtime. Ex-
Runtime Polymorphism i.e function overriding.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java Editions

J2SE J2ME J2EE


Java 2 Standard Edition Java 2 Micro Edition Java 2 Enterprise Edition

Java standard edition Java micro edition Java enterprise


is use to develop is use to develop edition is use to
client-side applications for develop server-side
standalone mobile devices such applications such as
applications or as cell phones Java servlets and Java
applets Server Pages

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

First “Hello World”


program using JAVA

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
“package sct”
● It is package declaration statement.
● defines a namespace in which classes are stored.
● to organize the classes based on functionality.
● If you omit the package statement, the class names are put into the
default package java.lang, which has no name.
● Package statement cannot appear anywhere in the program. It must be
the first line of your program.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
2. “public class HelloWorld”
● This line has various aspects of java programming.
● public: This is access modifier keyword which tells compiler access to
class. Various values of access modifiers can be public,
protected,private or default (no value).
● class: This keyword used to declare a class. Name of class (HelloWorld)
followed by this keyword.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
3. “Comments”
● Line comments: It starts with two forward slashes (//) and
continues to the end of the current line. Line comments do not
require an ending symbol.
● Block comments: start with a forward slash and an asterisk (/*) and
end with an asterisk and a forward slash (*/).Block comments can
also extend across as many lines as needed.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
4. “public static void main (String [ ] args)”:
● public: Access Modifier
● static: static is a reserved keyword which means that a method is
accessible and usable even though no objects of the class exist.
● void: This keyword declares nothing would be returned from the
method. The method can return any primitive or object.
● Method content inside curly braces. { }

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
5. System.out.println("Hello World from Java") :
● System: It is the name of Java utility class.
● out:It is an object which belongs to System class.
● println: It is utility method name which is used to send any String to the
console.
● “Hello World from Java”: It is String literal set as argument to println
method.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

ARRAY in JAVA Programming

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Introduction to Array Data Type

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Introduction to Array Data Type
● Arrays in Java are homogeneous data structures implemented in Java
as objects.
● Arrays store one or more values of a specific data type and provide
indexed access to store the same.
● A specific element in an array is accessed by its index.
● Arrays offer a convenient means of grouping related information.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Introduction to Array Data Type
● Obtaining an array is a two-step process.
○ First, you must declare a variable of the desired array type
○ Second, you must allocate the memory that will hold the array,
using new, and assign it to the array variable

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: General Form of Java Array Initialization

Example:- int month_days[];

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: General Form of Java Array Initialization

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: More About Array Initialization...

● Arrays can be initialized when they are declared.


● The array will automatically be created large enough to hold
the number of elements you specify in the array initializer.
● There is no need to use new.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: More About Array Initialization...

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: More About Array Initialization...

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Implementing an Array

class MyArray{ OUTPUT


April has 30days
public static void main(String args[]){

int month_days[ ] = {31,28,31,30,31,30,31,30,31,30,31};

System.out.println("April has " + month_days[3] + days.");

}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Accessing a Specific Element in a Java Array

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
public static void main(String args[]) {
int month_days[];
month_days = new int[12]; OUTPUT
month_days[0] = 31; April has 30days
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Multidimensional Array

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Multidimensional Array -Conceptually

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
class TwoDArray // Print the table
{ for (i=0; i < 4;i++)
//----------------------------------------------------------------- {
// Creates a 2D array of integers, fills it with increasing for (j=0; j < 5; j++)
// integer values, then prints them out. {
//----------------------------------------------------------------- System.out.print( multarry[i][j]+" ");
public static void main (String[] args) }
{
int[][] multarry = new int[4][5]; System.out.println();
int i,j,k=0;
}
// Load the table with values } OUTPUT
for (i=0; i < 4;i++) } 01234
for (j=0; j < 5; j++) 56789
{ 10 11 12 13 14
multarry[i][j]=k; 15 16 17 18 19
k++;
}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Multidimensional arrays representation of different data types.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Multidimensional arrays representation of different data types.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Array Vs ArrayList

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Array Vs ArrayList

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
JAVA: Passing Java Array to a Method
class PMethods{
public static void display(int y[])
{
System.out.println(y[0]);
System.out.println(y[1]);
System.out.println(y[2]);

} OUTPUT
public static void main(String args[]) 1
{ 2
int x[] = { 1, 2, 3 }; 3
display(x); //Passed array x to method display
}
}
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

Click Here

Java Interview Questions on Array

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Memory Allocation
and
Java Garbage Collection

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java Heap Space

● Used by Java runtime to allocate memory to Objects and JRE classes.


● Any new Object is always created in Heap Space.
● Garbage Collection runs on the heap memory to free the memory
used by objects that doesn’t have any reference.
● All instance and class variables are also stored in the heap.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Java Stack Memory
● Used for execution of a thread.
● Store method specific values, and “references” to Objects being used in the method.
● Stack memory is LIFO (Last-In-First-Out)
● Whenever a method is invoked, a new block is created in the stack memory for the
method to hold local primitive values and reference to other objects in the
method. As soon as method ends, the block becomes unused and become
available for next method.
● Stack memory size is very less compared to Heap memory.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


Page 4
SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


Page 4
SNJB’s Late Sau. K. B. J. College of Engineering

String Handling in Java

Department of Computer Engineering


Creating String in Java
There are two ways to create a String in Java
• String literal

• Using “new” keyword

Does it make any difference? Well, yes!


68
String Pool Concept in Java (String Interning)

69
String Intern Pool maintained in Java Heap Space
SNJB’s Late Sau. K. B. J. College of Engineering

Discussion: How many Strings are getting created here?

70
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

String is Immutable in Java


String s1 = "Sky";
String s2 = "Blue"

71
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

String is Immutable in Java

s1 = s1 + s2;

72
Department of Computer Engineering
String Pool Concept in Java (String Interning)
● String is immutable in Java
● All Strings are stored in String Pool (also called String Intern Pool) allocated
within Java Heap Space
● It is implementation of String Interning Concept.
● String interning is a method of storing only one copy of each distinct string
value, which must be immutable.
● Interning strings makes some string processing tasks more time- or space-
efficient at the cost of requiring more time when the string is created or
interned.
● The distinct values are stored in a string intern pool.
● Using new operator, we force String class to create a new String object in heap
space. 73
String Pool Concept in Java (String Interning)
public class InternExample{

public static void main(String args[]){

String s1=new String("hello");

String s2="hello";

String s3=s1.intern(); //returns string from pool, now it will be same as s2

System.out.println(s1==s2);//false because reference variables are pointing to different instance

System.out.println(s2==s3);//true because reference variables are pointing to same instance

}}
74
java.lang.String API – Important methods

75
java.lang.String API – Important methods

76
java.lang.String API – Examples

77
java.lang.String API – Examples
public class EqualsSample{
public static void main(String args[]){
String s1="string";
String s2="string";
String s3="swing";
String s4= “ ABC ”;

System.out.println(s1.equals(s2)); // true because both


are equal

System.out.println(s1.equals(s3)); //false because both


are not equal
78
java.lang.String API – Examples

System.out.println(s1.length()); // 5 is the length of s1

System.out.println(s1.compareTo(s2)); //0 as both are equal

System.out.println(s1.compareTo(s3)); //-3 as ‘t’ in s1 is less than


‘w’ in s2

System.out.println(s4.trim() +":wordpress.com");
//ABC.wordpress.com

System.out.println(s1.concat(s4)); //string ABC


79
System.out.println(s1.toUpperCase()); //STRING
java.lang.String API – Examples

System.out.println(s1.charAt(4)); // n

}
}

80
SNJB’s Late Sau. K. B. J. College of Engineering
Converting String to numbers and vice versa
● String to Number
○ int i = Integer.parseInt(str);
○ Integer i = Integer.valueOf(str);
○ double d = Double.parseDouble(str);
○ Double d = Double.valueOf(str);

Note: Both throw NumberFormatException If the String is not valid for conversion
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Converting String to numbers and vice versa
● String to Boolean
○ boolean b = Boolean.parseBoolean(str);

● Any Type to String


○ String s = String.valueOf(value);

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Click Here

Java Interview Questions on String

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Classes and Method

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

● Core of Java.
● Logical construct upon which the entire Java language is built
● Defines the shape and nature of and object.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Class Fundamentals
● A class is that it defines a new data type.
● Once defined, this new type can be used to create objects of that type.
● A class is a template for an object, and an object is an instance of a
class. Because an object is an instance of a class
● Two word object and instance used interchangeably.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The General Form of a Class
● The data that it contains
and the code that
operates on that data

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The General Form of a Class
● The data that it contains and the code that operates on that data
● The data, or variables, defined within a class are called instance
variables
● The code is contained within methods
● Collectively, the methods and variables defined within a class are
called members of the class.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The General Form of a Class
● Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the class)
contains its own copy of these variables.
● Thus, the data for one object is separate and unique from the data for
another.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The General Form of a Class
● All methods have the same general form as main( ).
● However, most methods will not be specified as static or public
● the general form of a class does not specify a main( ) method.
● Java classes do not need to have main( ) method. You only specify one if
that class is the starting point for your program.
● Further ,some kinds of Java applications, such as applets, don’t
require a main( ) method at all.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A Simple Class

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Declaring Objects
● Obtaining objects of a class is a two-step process.
● First, you must declare a variable of the class type. This variable does
not define an object. Instead,it is simply a variable that can refer to an
object.
● Second, you must acquire an actual, physical copy of the object and
assign it to that variable. You can do this using the new operator.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Declaring Objects
● The new operator dynamically allocates (that is, allocates at run
time) memory for an object and returns a reference to it.
● This reference is, more or less, the address in memory of the object
allocated by new
● This reference is then stored in the variable. Thus, in Java, all class
objects must be dynamically allocated.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A Closer Look at new
● The new operator dynamically allocates (that is, allocates at run
time) memory for an object.
● It has this general form:

class-var = new classname ( );

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A Closer Look at new
● The class name followed by parentheses specifies the constructor for
the class.
● A constructor defines what occurs when an object of a class is created.
● Constructors are an important part of all classes and have many
significant attributes.
● Most real-world classes explicitly define their own constructors within
their class definition.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A Closer Look at new
● if no explicit constructor is specified, then Java will automatically supply a default
constructor
● Java’s primitive types are not implemented as objects. Rather, they are implemented as
“normal” variables.
● Advantage of new : program can create as many or as few objects as it needs during
the execution of your program.
● memory is finite, it is possible that new will not be able to allocate memory for an object
because insufficient memory exists.
● If this happens, a run-time exception will occur.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Assigning Object Reference Variables

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Assigning Object Reference Variables

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Assigning Object Reference Variables
REMEMBER
When you assign one object reference variable to another
object reference variable, you are not creating a copy of the
object, you are only making a copy of the reference.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Methods
general form of a method:

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Adding a Method to the Class

● In fact, methods define the interface to most classes. This allows the
class implementor to hide the specific layout of internal data
structures behind cleaner method abstractions.
● In addition to defining methods that provide access to data,you can
also define methods that are used internally by the class itself.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Adding a Method to the Class

● The instance variables width, height, and depth are referred to


directly,
● without preceding them with an object name or the dot operator.
● When an instance variable is accessed by code that is not part of the
class in which that instance variable is defined, it must be done through
an object, by use of the dot operator.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Returning a Value

● The type of data returned by a method must be compatible with the


return type specified by the method.
● For example, if the return type of some method is boolean , you could not
return an integer.
● The variable receiving the value returned by a method (such as vol
in this case) must also be compatible with the return type specified for
the method

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Returning a Value

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Adding a Method That Takes Parameters

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Returning a Value

● A parameter is a variable defined by a method that receives a value


when the method is called.
● For example, in square( ) , i is a parameter.
● An argument is a value that is passed to a method when it is invoked.
For example, square(100) passes 100 as an argument.
● Inside square( ) , the parameter i receives that value.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Modified program using parameterized methods

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Constructor

● A constructor initializes an object immediately upon creation.


● It has the same name as the class in which it resides and is syntactically
similar to a method.
● Once defined, the constructor is automatically called when the object is
created, before the new operator completes.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Constructor

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Constructor
● The default constructor automatically initializes all instance variables to
their default values,
○ which are zero for numeric types,
○ null for reference types ,
○ and false for boolean
● The default constructor is often sufficient for simple classes, but it usually
won’t do for more sophisticated ones.
● Once you define your own constructor, the default constructor is no
longer used.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Parameterized Constructor

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The this Keyword

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The this Keyword The this Keyword and
Instance Variable Hiding

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The this Keyword
● Sometimes a method will need to refer to the object that invoked it. To allow
this, Java defines the this keyword.
● This can be used inside any method to refer to the current object.
● That is, this is always a reference to the object on which the method was
invoked.
● You can use this any where a reference to an object of the current class’
type is permitted.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Instance Variable Hiding
● Java to declare two local variables with the same name inside the same or
enclosing scopes.
● Interestingly, you can have local variables, including formal parameters
to methods, which overlap with the names of the class’ instance variables.
● Because this lets you refer directly to the object, you can use it to resolve any
namespace collisions that might occur between instance variables and local
variables.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The this Keyword and Instance Variable Hiding
● The use of this in such a context can sometimes be confusing, and some
programmers are careful not to use local variables and formal parameter
names that hide instance variables.
● Of course,other programmers believe the contrary—that it is a good
convention to use the same names for clarity, and use this to overcome
the instance variable hiding.
● It is a matter of taste which approach you adopt.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Garbage Collection
● It is automatic deallocation.
● when no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by the object can be reclaimed.
● There is no explicit need to destroy objects as in C++.
● only occurs sporadically (ifat all) during the execution of your program.
● It will not occur simply because one or more objects exist that are no longer used.
● different Java run-time implementations will take varying approaches to garbage
collection, but for the most part, you should not have to think about it while
writing your programs.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The finalize( ) Method

● Sometimes an object will need to perform some action when it is


destroyed.
● For example, if an object is holding some non-Java resource such as a file
handle or character font, then you might want to make sure these resources
are freed before an object is destroyed.
● To handle such situations, Java provides a mechanism called finalization
● you can define specific actions that will occur when an object is just
about to be reclaimed by the garbage collector.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
The finalize( ) Method
● To add a finalizer to a class, you simply define the finalize( ) Method.
● The Java run time calls that method whenever it is about to recycle an object
of that class.
● Inside the finalize( ) method, you will specify thos eactions that must be
performed before an object is destroyed.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
The finalize( ) Method
● It is important to understand that finalize( ) is only called just prior to
garbage collection.
● It is not called when an object goes out-of-scope
● For example. This means that you cannot know when—or even if—finalize( )
will be executed. Therefore, your program should provide other means of
releasing system resources, etc., used by the object.
● It must not rely on finalize( ) for normal program operation

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Polymorphism in Java

● The process of representing one form in multiple forms is known as

Polymorphism.

● Polymorphism is derived from 2 greek words: poly and morphs.

● The word "poly" means many and "morphs" means forms. So

polymorphism means many forms.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Unit 3
Java as Object Oriented Programming Language-Overview
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.
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Polymorphism in Java

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Polymorphism in Java

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Polymorphism in Java

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading

● In Java it is possible to define two or more methods within the same class
that share the same name, as long as their parameter declarations are different
● When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded
method to actually call
● The return type alone is insufficient to distinguish two versions of a
method.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading and automatic Type Promotion

● In some cases Java’s automatic type conversions can


play a role in overload resolution
● Java will employ its automatic type conversions only if
no exact match is found

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading and automatic Type Promotion

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Method Overloading and automatic Type Promotion

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Constructor Overloading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Constructor Overloading

● Java Constructor overloading is a technique in which a class


can have any number of constructors that differ in
parameter list.
● The compiler differentiates these constructors by taking into
account the number of parameters in the list and their
type.
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Constructor Overloading

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Objects as Parameters

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Copy constructor

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A closer look at argument Passing
There are two ways that a computer language can pass an
argument to a subroutine
● Call by value
● Call by reference

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A closer look at argument Passing

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
A closer look at argument Passing

Call by Value : When a primitive type is passed to a method


Call by Reference : objects are implicitly passed to a method

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Returning Objects

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Unit 3
Java as Object Oriented Programming Language-Overview
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.
Departmentof
Department ofComputer
ComputerEngineering
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
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

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Recursion
● Recursive versions of many routines may execute a bit more slowly
than the iterative equivalent because of the added overhead of the
additional function calls
● Because storage for parameters and local variables is on the stack
and each new call creates a new copy of these variables, it is
possible that the stack could be exhausted
● If this occurs, the Java run-time system will cause an exception

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Recursion
● The main advantage to recursive methods is that they can be used to
create clearer and simpler versions of several algorithms than
can their iterative relatives

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Recursion

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Access Control
● Java’s access specifiers are public, private, and protected
● protected applies only when inheritance is involved
● When a member of a class is modified by the public specifier,
then that member can be accessed by any other code
● When a member of a class is specified as private, then that
member can only be accessed by other members of its class

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Access Control

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Access Control
● Java’s access specifiers are public, private, and protected
● protected applies only when inheritance is involved
● When a member of a class is modified by the public specifier,
then that member can be accessed by any other code
● When a member of a class is specified as private, then that
member can only be accessed by other members of its class

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Access Control

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Understanding static
● When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any object
● The most common example of a static member is main( )
● main( ) is declared as static because it must be called before any
objects exist
● Instance variables declared as static are, essentially, global
variables

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Methods declared as static have several restrictions:
● They can only call other static methods
● They must only access static data
● They cannot refer to this or super in any way

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Methods declared as static have several restrictions:
● They can only call other static methods
● They must only access static data
● They cannot refer to this or super in any way
● We can declare a static block which gets executed exactly once,
when the class is first loaded

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Understanding static

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing final
● A variable can be declared as final
● Doing so prevents its contents from being modified
● We must initialize a final variable when it is declared
● final int FILE_NEW = 1;
● final int FILE_OPEN = 2;

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing final
● Variables declared as final do not occupy memory on a per-
instance basis
● The keyword final can also be applied to methods, but its
meaning is substantially different than when it is applied to
variables

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes
● It is possible to define a class within another class
● The scope of a nested class is bounded by the scope of its
enclosing class
● If class B is defined within class A, then B is known to A, but not
outside of A
● A nested class has access to the members, including private
members, of the class in which it is nesteD

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes
● However, the enclosing class does not have access to the
members of the nested class
● There are two types of nested classes: static and non-static
● A static nested class is one which has the static modifier applied
● static innerclass must access its enclosing class by creating an
object.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes
● The most important type of nested class is the inner class
● An inner class is a non-static nested class
● It has access to all of the variables and methods of its outer class

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes
● It is important to realize that class Inner is known only within
the scope of class Outer
● The Java compiler generates an error message if any code
outside of class Outer attempts to instantiate class Inner

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes
● It is important to realize that class Inner is known only within
the scope of class Outer
● The Java compiler generates an error message if any code
outside of class Outer attempts to instantiate class Inner
● While nested classes are not used in most day-to-day programming,
they are particularly helpful when handling events in an applet

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes
● It is important to realize that class Inner is known only within
the scope of class Outer
● The Java compiler generates an error message if any code
outside of class Outer attempts to instantiate class Inner
● While nested classes are not used in most day-to-day programming,
they are particularly helpful when handling events in an applet

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Introducing Nested and Inner Classes

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Example of Nested Class
class TestMemberOuter1{

private int data=30; public static void main(String args[]){

class Inner{ TestMemberOuter1 obj=new


TestMemberOuter1();
void msg(){System.out.println("data is "+data);}
/)msg() complete TestMemberOuter1.Inner in=obj.new Inner();

} // Inner class Complete in.msg();

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Command Line Argument

● The java command-line argument is an argument i.e. passed at


the time of running the java program.
● The arguments passed from the console can be received in the
java program and it can be used as an input.
● So, it provides a convenient way to check the behavior of the
program for the different values. You can pass N (1,2,3 and so
on) numbers of arguments from the command prompt.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Command Line Argument
● When command-line arguments are supplied to JVM, JVM wraps

these and supplies them to args[]. It can be confirmed that they are

actually wrapped up in an args array by checking the length of args

using args.length.

● Internally, JVM wraps up these command-line arguments into the

args[ ] array that we pass into the main() function. We can check

these arguments using args.length


Department of Computermethod. JVM stores the first
Engineering
SNJB’s Late Sau. K. B. J. College of Engineering
Using Command-Line Arguments

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Program for Command Line argument

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Steps to Run COmmand Line Argument
Save the program as Hello.java

Open the command prompt window and compile the program- javac Hello.java

After a successful compilation of the program, run the following command by


writing the arguments- java Hello

For example – java Hello Geeks at GeeksforGeeks

Press Enter and you will get the desired output.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Command Line Argument

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Var args-Variable length Arguments

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Variable Arguments
A method with variable length arguments(Varargs) in Java can
have zero or multiple arguments.

Variable length arguments are most useful when the number of


arguments to be passed to the method is not known beforehand.

They also reduce the code as overloaded methods are not


required.

Department of Computer Engineering


SNJB’s Late Sau. K. B. J. College of Engineering
Variable Arguments
public class Demo {

public static void Varargs(String... str) {

System.out.println("\nNumber of arguments are: " +


str.length);

System.out.println("The argument values are: ");

for (String s : str)

System.out.println(s);
Department of Computer Engineering
SNJB’s Late Sau. K. B. J. College of Engineering

public static void


main(String args[]) {

Varargs("Apple",
"Mango", "Pear");

Varargs();

Varargs("Magic");

} Department of Computer Engineering

You might also like