Upload
priyam
View
3
Download
0
Embed Size (px)
DESCRIPTION
ppt regarding introduction concepts of java and oop.
Citation preview
INTRODUCTION TO JAVA PROGRAMMING
Java: Write Once, Run Anywhere (3)
• Java has been used by large and reputable companies to create serious stand-alone applications.
• Example:– Eclipse1: started as a programming environment created by IBM for
developing Java programs. The program Eclipse was itself written in Java.
1 For more information: http://www.eclipse.org/downloads/
Java Development Kit (JDK)
It is a collection of development tools.
These are used for developing and running java
programs.
Components of JDK Javac (Java compiler)
Java (Java Interpreter)
Javap (Java disassembler- disassembles one or more class files)
Javah (for cretaing C header files or source or output files)
Javadoc (for creating HTML documents)
Appletviewer (for viewing Java applets)
Jdb (Java Debugger)
Text Editor
Java Source Code
javac
Java Class File
java
Output
javadoc
javah
jdb
HTML Files
Header Files
Process of Building and Running Java Programs
Java Runtime Environment vs. Java Development Kit
A Java distribution comes typically in two flavors, the Java Runtime Environment (JRE) and the Java Development Kit (JDK).
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler etc.
Java Virtual Machine(JVM)
• The JVM is the environment in which Java programs execute.• It is a software that is implemented on top of real hardware and
operating system. • When the source code (.java files) is compiled, it is translated into
byte codes and then placed into (.class) files. • The JVM executes these bytecodes. So Java byte codes can be
thought of as the machine language of the JVM. • A JVM can either interpret the bytecode one instruction at a time or
the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler (e.g Oracle JRockit JVM )
• The JVM must be implemented on a particular platform before compiled programs can run on that platform.
The Java SDK comes in three versions: J2ME - Micro Edition (for handheld and portable devices) J2SE - Standard Edition (PC development) J2EE - Enterprise Edition (Distributed and Enterprise Computing)
The SDK is a set of command line tools for developing Java applications: javac - Java Compiler java - Java Interpreter (Java VM) appletviewer - Run applets without a browser javadoc - automated documentation generator jdb - Java debugger
The SDK is NOT an IDE (Integrated Development Environment) Command line only. No GUI.
The Java Software Development Kit (SDK)
While it should be your goal to learn as many packages as you can, there are some packages you will use more than others:
Commonly Used Packages
Language(general)
GUI
Misc. Utilities and Collections
Input/Output
Networking
java.lang
java.awtjava.awt.eventjavax.swing
java.util
java.io
java.net
Common classes used for all application development
Graphical User Interface, Windowing,Event processing
Helper classes, collections
File and Stream I/O
Sockets, Datagrams
FIRST JAVA PROGRAMCOMPILING AND EXECUTING
Getting Started(1) Create the source file:
– open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a file (HelloWorldApp.java)
– file and class name are case sensitive and must be matched exactly (except the .java part)
Example Code: HelloWorldApp.java
public class HelloWorldApp {
public static void main(String[] args) {
// Display "Hello World!" System.out.println("Hello World!");
} }
Java is CASE SENSITIVE!
Getting Started(2) Compile the program:
– compile HelloWorldApp.java by using the following command:
javac HelloWorldApp.java
it generates a file named HelloWorldApp.class
‘javac’ is not recognized as an internal or external command, operable program or batch file. javac: Command not found
if you see one of these errors, you have two choices:1) specify the full path in which the javac program locates every time. For example:
C:\j2sdk1.4.2_09\bin\javac HelloWorldApp.java
2) set the PATH environment variable
Getting Started(3) Run the program:
– run the code through:java HelloWorldApp
– Note that the command is java, not javac, and you refer toHelloWorldApp, not HelloWorldApp.java or HelloWorldApp.class
Exception in thread "main" java.lang.NoClassDefFoundError:HelloWorldApp
if you see this error, you may need to set the environment variable CLASSPATH.
Explaining first program
public class HelloWorldApp {
public static void main(String[] args) {
// Display "Hello World!" System.out.println("Hello
World!"); } }
public: so that JVM can access the main method
static: so that JVM can call main method w/o creating object.
void : no return type
main: starting point
String args[] : command line arguments in form of string array.
Explaining first programpublic class HelloWorldApp {
public static void main(String[] args) {
// Display "Hello World!" System.out.println("Hello World!");
} }
Inbuilt class in Java.lang package
Object of printStream class
Is a method of printstream class
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java is partially modeled on C++, but greatly simplified and improved. Some people refer to Java as "C++--" because it is like C++ but with more functionality and fewer negative aspects.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented programming (OOP) is a popular programming approach that is replacing traditional procedural programming techniques.
One of the central issues in software development is how to reuse code. Object-oriented programming provides great flexibility, modularity, clarity, and reusability through encapsulation, inheritance, and polymorphism.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Distributed computing involves several computers working together on a network. Java is designed to make distributed computing easy. Since networking capability is inherently integrated into Java, writing network programs is like sending and receiving data to and from a file.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
You need an interpreter to run Java programs. The programs are compiled into the Java Virtual Machine code called bytecode. The bytecode is machine-independent and can run on any machine that has a Java interpreter, which is part of the Java Virtual Machine (JVM).
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java compilers can detect many problems that would first show up at execution time in other languages.
Java has eliminated certain types of error-prone programming constructs found in other languages.
Java has a runtime exception-handling feature to provide programming support for robustness.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java implements several security mechanisms to protect your system against harm caused by stray programs.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Write once, run anywhere
With a Java Virtual Machine (JVM), you can write one program that will run on any platform.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java’s performance Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading.
Characteristics of Java• Java Is Simple • Java Is Object-Oriented • Java Is Distributed • Java Is Interpreted • Java Is Robust • Java Is Secure • Java Is Architecture-Neutral • Java Is Portable • Java's Performance • Java Is Multithreaded • Java Is Dynamic
Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation. There is no need for developers to create, and for users to install, major new software versions. New features can be incorporated transparently as needed.
JAVA AND C++Main Differences
Java vs C++• Java is (an interpreted) write once, run anywhere language.
- Write once, run everywhere does (nearly) NEVER work with C++, but does (nearly) ALWAYS work with JAVA.
- Acheived using bytecode concept.
• You don't have separated HEADER-files defining class-properties– You can define elements only within a class.
– All method definitions are also defined in the body of the class.
– File- and classname must be identical in JAVA
– Instead of C++ “#include“ you use the “import keyword“.• For example: import java.awt.*;.
• #include does not directly map to import, but it has a similar feel to it
JAVA vs C++
• Instead of controlling blocks of declarations like C++ does, the access specifiers (public, private, and protected) are placed on each definition for each member of a class– Without an explicit access specifier, an element defaults to "friendly,"
which means that it is accessible to other elements in the same package (which is a collection of classes being ‘friends‘)
– The class, and each method within the class, has an access specifier to determine whether it’s visible outside the file.
JAVA vs C++
• Everything must be in a class.– There are no global functions or global data. If you want the equivalent
of globals, make static methods and static data within a class.
– There are no structs or enumerations or unions, only classes.
– Class definitions are roughly the same form in Java as in C++, but there’s no closing semicolon.
• Java has no preprocessor. – If you want to use classes in another library, you say import and the
name of the library.
– There are no preprocessor-like macros.
– There is no conditional compiling (#ifdef)
JAVA vs C++
• All the primitive types in Java have specified sizes that are machine independent for portability. - The char type uses the international 16-bit Unicode character set, so it
can automatically represent most national characters.
• Type-checking and type requirements are much tighter in Java. – For example:
• 1. Conditional expressions can be only boolean, not integral.• 2. The result of an expression like X + Y must be used; you can’t just say "X
+ Y" for the side effect.
JAVA vs C++
• There are Strings in JAVA– Strings are represented by the String-class, they aren‘t only some
renamed pointers– Static quoted strings are automatically converted into String objects. – There is no independent static character array string like there is in C
and C++.
• There are no Java pointers in the sense of C and C++
JAVA vs C++
• Although they look similar, arrays have a very different structure and behavior in Java than they do in C++.– There’s a read-only length member that tells you how big the array is, and
run-time checking throws an exception if you go out of bounds.
– All arrays are created on the heap, and you can assign one array to another (the array handle is simply copied).
• There is a garbage collection in JAVA– Garbage collection means memory leaks are much harder to cause in Java,
but not impossible.
• There are no destructors in Java. – There's no need because of garbage collection.
JAVA vs C++
• Java has method overloading, but no operator overloading.
• Java has both kinds of comments like C++ does.
• There’s no goto in Java. – The one unconditional jump mechanism is the break label or continue
label, which is used to jump out of the middle of multiply-nested loops.
• Java contains standard libraries for GUIs– Simple, robust and effective way of creating user-interfaces– Graphical output as part of the language
Features of C++ omitted in JAVA1. No Typedef, pre-processor(#define,#include), Structure &
Unions.2. No standalone functions, global functions, global data
everything in a class.3. Member functions to be defined only inside a class (No
inline functions)4. No goto and delete keyword used.5. No default arguments to functions.6. Objects are passed by reference only not by value but
references are themselves values.7. No Pointers so no use of :: & -> operators8. No Multiple Inheritance interfaces instead.9. No forward declaration, no semicolon at end of class.
Features of C++ omitted in JAVA10. No automatic type conversion that results in loss of
precision.11. Primitive data type size is same for all platforms12. No copy constructors as all objects are passed by references
only.13. No destructors as work done automatically by Garbage
collector..14. No declaration of static member outside class.15. Interpretation of private, public and protected keyword is
different.16. No Templates but support collections/generics17. No virtual functions all dynamic binding (final keyword)18. No Operator Overloading.
28/04/2023 BY: Raju Pal 37
Lexical Issues
• There are many atomic elements of Java. Java programs are a collection of whitespace, identifiers, comments, literals, operators, separators and keywords.
• Whitespace– Java is a free-form language. It means we do not need to follow any special
indentation rules. In java whitespace is a space, tab, or newline.• Identifiers
– Identifiers are used for class names, method names and variable names.– An identifier may be any descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollor-sign characters.• Eg: AvgTemp, count, $calculate, s5, value_display
– An identifier must not begin with a number because it leads to invalid indentifier.• Eg: 5s, yes/no
28/04/2023 BY: Raju Pal 38
Lexical Issues
• Literals– A constant value in Java is created by using a literal representation. A literal is
allowed to use anywhere in the program.
Eg: Integer literal : 100 Floating-point literal : 98.6 Character literal : ‘s’ String literal : “sample”
• Comments// This comment extends to the end of the line./*..............the multi-line comments are given with in this comment............................................................................................................*//**....... Documentation comments..........*/(readable to both human and computer)
28/04/2023 BY: Raju Pal 39
Lexical Issues• Separators
Separators are used to terminate statements. In java there are few characters are used as separators . They are, parentheses(), braces{}, brackets[], semicolon;, period., and comma,.
• Java Keywords ( 49 )
28/04/2023 BY: Raju Pal 40
Data Types
• Data type specify the size and type of values• Java defines eight simple types of data. These can be put into
four groups:1. Integers2. Floating-point numbers3. Characters4. Boolean
Range: -2x-1 to 2x-1-1 where x is number of bits.
Leftmost bit is reserved for the sign.
28/04/2023 BY: Raju Pal 41
Data Types Integers
Floating-point
Name Width(Size) Rangebyte 8 bits -128 to 127short 16 bits -32768 to 32767int 32 bits -2147483648 to 2147483647long 64 bits -264-1 to 264-1 -1
Name Width(Size) Rangefloat 32 bits 1.4e-045 to 3.4e+038double 64 bits 4.9e-324 to 1.8e+038
28/04/2023 BY: Raju Pal 42
Data Types
Characters• A char variable stores a single character from the Unicode
character set• A character set is an ordered list of characters, and each
character corresponds to a unique number• Unicode is an international character set, containing symbols
and characters from many world languages• The Unicode character set uses 16 bits per character, allowing
for 65,536 unique characters• Character literals are enclosed in single quotes:• ‘A' ‘c' ‘3' '$' ‘.' '\n‘
28/04/2023 BY: Raju Pal 43
Data Types
• You might have heard about the ASCII character set • ASCII is older and smaller than Unicode, but is still quite popular• The ASCII characters are a subset of the Unicode character set, including:
• uppercase letters A, B, C, …• lowercase letters a, b, c, …• digits 0, 1, 2, …• special symbols *, &, +, ?, …• control characters backspace ‘\b’• escape sequences) new line ‘\n’, …
Characters• Data type used to store character is char. • It requires 16 bits.• Range of a char is 0 to 65536 (no negative char)
28/04/2023 BY: Raju Pal 44
Data Types
Boolean• Used to test a particular condition• It can take only two values: true and false• Uses only 1 bit of storage• All comparison operators return boolean value
28/04/2023 BY: Raju Pal 45
Constants
• Refer to fixed values that do not change during the execution of a program.
• Integer Constants: sequence of digits• 123 037 0X2
• Real Constants: numbers containing fractional parts• 0.0083 -0.75 435.36
• Single character Constants: single character• ‘5’ ‘A’ ‘;’
• String Constants: sequence of characters• “Hello World”“?+;;;;….#”
• Backslash character (Symbolic) Constants: used in output methods• ‘\n’ ‘\b’ ‘\t’ ‘\’’ ‘\\”’ ‘\\’
28/04/2023 BY: Raju Pal 46
Constants
28/04/2023 BY: Raju Pal 47
Symbolic Constants
• Some constants may appear repeatedly in a number of places in
the program.
• These constants can be defined as a symbolic name
• Make a program:
• easily modifiable
• More understandable– final type symbolic name = valueex: final float PI = 3.14159
28/04/2023 BY: Raju Pal 48
Variables
• An identifier that denotes a storage location used to store a data value.• May take different values at different times during the execution of the
program• Naming Conventions: may consists of alphabets, digits, underscore and dollar
with following conditions• Must not begin with a digit• Uppercase and Lowercase are distinct.• Should not be a keyword• Space is not allowed
• Variable declaration and assignment– <type> variable_name;– Variable_name =value; // initializtaion– Variable_name=Math.sqrt(Variable_name* Variable_name);//
dynamic initialization
28/04/2023 BY: Raju Pal 49
Scope of Variables
Classified into three kinds:• Instance Variables
• Created when the objects are instantiated• Take different values for each object
• Class Variables• Global to a class• Belong to the entire set of objects that class creates• Only one memory location is created
• Local Variables• Used inside methods or inside program blocks.• Blocks are defined between opening brace { and a closing brace }• Visible to program only from the beginning to the end of the block.
28/04/2023 BY: Raju Pal 50
Type Casting
• The process of converting one data type to another is called casting
type variable1 = (type) variable2
int m = 50;
byte n = (byte) m• Casting into a smaller type may result in a loss of data• Automatic Conversion:(smaller to larger-promotion)
Automatic type conversion is possible only if the destination type has enough space to store the source value.
28/04/2023 BY: Raju Pal 51
Type Casting
Type Casting
Widening (implicit)
Narrowing (Explicit)
Assigning a smaller type to a larger oneNo need to write anything (automatic conversion)
byte b = 75int a =b
Assigning a larger type to a smaller oneWrite the target data type within parenthesis
int a = 75byte b = (byte) a
28/04/2023 BY: Raju Pal 52
Type Casting
28/04/2023 BY: Raju Pal 53
Type Casting
28/04/2023 BY: Raju Pal 54
Type Casting
28/04/2023 BY: Raju Pal 55
Array Array is a list of finite number n of homogeneous data elements
such that:
• The elements of the array are referenced respectively
by an index set of n consecutive numbers.
• The element of the array are stored respectively in
successive memory location.
• The number n of elements is called the length or size.
28/04/2023 BY: Raju Pal 56
Creation of Arrays• After declaring arrays, we need to allocate memory for
storage array items.• In Java, this is carried out by using “new” operator, as
follows:Arrayname = new type[size];
• Examples: students = new int[7];
Declaring and defining in the same statement:int[] students=new students[10];double myList[] = new double[10];
0123456
students
28/04/2023 BY: Raju Pal 57
Initialization of Arrays1. Once arrays are created, they need to be initialised with
some values before access their content. A general form of initialisation is:
Arrayname [index/subscript] = value;2. Example:
students[0] = 50;students[1] = 40;
3. Array index starts with 0 and ends with n-14. Trying to access an array beyond its
boundaries will generate an error message.students[7] = 100;
50students
0123456
28/04/2023 BY: Raju Pal 58
Explicit initialization1. Arrays can also be initialised like standard variables at the time of their
declaration.
Type arrayname[] = {list of values};
2. Example:
int[] students = {55, 69, 70, 30, 80, 90, 45};
3. Creates and initializes the array of integers of length 7.
4. In this case it is not necessary to use the new operator.
55697030809045
students
0123456
28/04/2023 BY: Raju Pal 59
Array: Default ValuesWhen an array is created, its elements are assigned the default value of
0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types
Once an array is created, its size is fixed. It cannot be changed. You can find its size using
arrayRefVar.length
28/04/2023 BY: Raju Pal 60
Processing Array Elements using loop• Often a for( ) loop is used to process each of the elements of the array in
turn.
• The loop control variable, i, is used as the index to access array components
28/04/2023 BY: Raju Pal 61
Array as Parameters• Methods can accept arrays via parameters• Use square brackets [ ] in the parameter declaration:
28/04/2023 BY: Raju Pal 62
Returning Array
• A method may return an array as its result
double [] readArray(int n){
double result[] = new double[n]; for (i = 0; i < n; i++){
result[i] = i;}return result;
}
28/04/2023 BY: Raju Pal 63
Two Dimensional Arrays• Two dimensional arrays allows us to store data that are recorded in
table.int[][] student=new int[4][4];4 arrays each having 4 elementsFirst index: specifies array (row)Second Index: specifies element in that array (column)
10 20 85 45
56 58 25 58
45 85 65 78
65 14 28 56
0 1 2 3
0
1
2
3
28/04/2023 BY: Raju Pal 64
Accessing 2D Array Elements Sum the Elements
• Here is code that sums all the numbers in table. • The outer loop iterates four times and moves down the
rows. • Each time through the outer loop, the inner loop iterates
five times and moves across a different row.
28/04/2023 BY: Raju Pal 65
Declaration and Instantiation of 2D Array
Declaring and instantiating two-dimensional arrays are accomplished by extending the processes used for one-dimensional arrays:
• Declaration:int myArray [][];
• Creation or Instantiation:myArray = new int[4][3]; // ORint myArray [][] = new int[4][3];
• Initialisation:- Single Value;
myArray[0][0] = 10;- Multiple values:
int table[2][3] = {{10, 15, 30}, {14, 30, 33}};int table[][] = {{10, 15, 30}, {14, 30, 33}};
28/04/2023 BY: Raju Pal 66
2D Array as “Array of Arrays”
int table [][] = new int[4][5];• The variable table references an array of four elements. • Each of these elements in turn references an array of five integers.
Variable Size Arrays
28/04/2023 BY: Raju Pal 67
Java treats multidimensional arrays as “arrays of arrays”. It is possible to declare a 2D arrays as follows:
[0]
[1]
[2]
int a[][] = new int [3][];
a[0]= new int [2];
a[1]= new int [3];
a[2]= new int [4];
[0] [1]
[0] [1] [2]
[0] [1] [2] [3]
28/04/2023 BY: Raju Pal 68
Multidimensional ArraysExample: A farmer has 10 farms of beans each in 5
countries, and each farm has 30 fields!Three-dimensional array:
long[][][] beans=new long[5][10][30];//beans[country][farm][fields]
28/04/2023 BY: Raju Pal 69
Varying length in Multidimensional Arrays
Same features apply to multi-dimensional arrays as those of 2
dimensional arrays
long beans=new long[3][][]; //3 countries
beans[0]=new long[4][]; //First country has 4 farms
beans[0][4]=new long[10];//Each farm in first country has 10
fields
28/04/2023 BY: Raju Pal 70
Exercise-11. WAP in Java that create an array and simple print the element of the array.
(Array Traversing).2. WAP in Java that implements following three methods:
1. boolean Search( int [] A, int Key): it takes an array A and a Key as input and returns true if Key is in the array else return false.
2. int Position(int [] A, int Key): it takes an array A and a Key as input and returns the position of Key in the array.
3. int [] Sort(int [] A): it takes an array A and returns another array. The output array has same element as in input array but in ascending order.
3. WAP in Java that takes an two dimensional array as input parameter to a method and returns one dimensional array. Each element of the output array is the sum of the element of corresponding row in input array.
4. WAP in Java to add, multiply, and subtract two Matrices. The decision of operation should be made based on user’s choice.
28/04/2023 BY: Raju Pal 71
Classes
•A class is a user-defined data type. Once defined, this new type can be used to create variables of that type.
•These variables are termed as instances of classes, which are the actual objects.
•A class is a template for an object, and an object is an instance of a class.
28/04/2023 BY: Raju Pal 72
Classes and Objects
• An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.
Class Name: Circle Data Fields:
radius is _______ Methods:
getArea
Circle Object 1 Data Fields:
radius is 10
Circle Object 2 Data Fields:
radius is 25
Circle Object 3 Data Fields:
radius is 125
A class template
Three objects of the Circle class
28/04/2023 BY: Raju Pal 73
Class cont..//Basic form of a class
class classname{
type variable1type variable2-------------------------------type
methodname1(parameter_list){
//body of method}type
methodname2(parameter_list){
//body of method}---------------
}
//A Simple Classclass Box{
double width
double height
double depth
}
Data is encapsulated in a class by placing data fields inside the body of the class definition.
28/04/2023 BY: Raju Pal 74
Declaring (creating) ObjectsDeclaring Object Reference Variables
ClassName objectReference;
Example: Box myBox;
Creating Objects
objectReference = new ClassName();
Example: myBox = new Box();
The object reference is assigned to the object reference variable.
Declaring/Creating Objects in a Single Step
ClassName objectReference = new ClassName();
Example: Box myBox = new Box();
28/04/2023 BY: Raju Pal 75
Accessing Objects
• Referencing the object’s data:
objectRefVar.data
e.g., myBox.width
myBox.height
myBox.depth
• Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myBox.getArea()
28/04/2023 BY: Raju Pal 76
Classes and ObjectsTrace Code
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
Declare myBox
nullmyBox
28/04/2023 BY: Raju Pal 77
Classes and ObjectsTrace Code, cont.
nullmyBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
Create a Box
28/04/2023 BY: Raju Pal 78
Classes and ObjectsTrace Code, cont.
myBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
reference value
Assign object reference to myBox
28/04/2023 BY: Raju Pal 79
Classes and Objects
yourBox
reference valuemyBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
null
Declare yourBox
Trace Code, cont.
28/04/2023 BY: Raju Pal 80
Classes and Objects
Create a new Box object
yourBox
reference valuemyBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
null
Box
Width HeightDepth
Trace Code, cont.
28/04/2023 BY: Raju Pal 81
Classes and Objects
yourBox
reference valuemyBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
Box
Width HeightDepth
Trace Code, cont.
Assign object reference to yourBox
reference value
28/04/2023 BY: Raju Pal 82
Classes and Objects
yourBox
reference valuemyBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
Trace Code, cont.
reference value
Box
Width =100Height=10Depth =50
Change variables in yourBox
28/04/2023 BY: Raju Pal 83
Classes and ObjectsTrace Code, cont.
yourBox
reference valuemyBox
Box
Width HeightDepth
Box myBox = new Box();
Box yourBox = new Box();
yourBox.width = 100;
yourBox.height = 10;
yourBox.depth= 50;
myBox = yourBox; reference value
Box
Width =100Height=10Depth =50
Assigning Object Reference Variables
28/04/2023 BY: Raju Pal 84
Garbage Collection• When no references to an object exist, that object is assumed too
be no longer needed, and the memory occupied by the object can be reclaimed.
• As shown in the previous figure, after the assignment statement myBox = yourBox, myBox points to the same object referenced by yourBox. The object previously referenced by myBox is no longer referenced. This object is known as garbage. Garbage is automatically collected by JVM.
• If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any variable.
28/04/2023 BY: Raju Pal 85
The finalize() Method• Sometimes an object will need to perform some action when it is
destroyed.
• The garbage collector calls a special method named finalize in your object if that method exists.
• If an object hold some non-Java resources (file handle or window character font) or any reference to other objects, these resources can be freed using finalize method.
• Avoiding circular reference.
protected void finalize(){//finalization code here
}
28/04/2023 BY: Raju Pal 86
Differences between Variables of Primitive Data Types and Object Types
1
c: Circle
radius = 1
Primitive type int i = 1 i
Object type Circle c c reference
Created using new Circle()
28/04/2023 BY: Raju Pal 87
Copying Variables of Primitive Data Types and Object Types
1
c1: Circle
radius = 5
Primitive type assignmenti = j
Before:
i
2j
2
After:
i
2j
Object type assignmentc1 = c2
Before:
c1
c2
After:
c1
c2
c2: Circle
radius = 9
28/04/2023 BY: Raju Pal 88
Introducing Methodstype name(parameter-list){
//body of methodreturn value; (if type is not void)
}
• Define the interface to most classes.• Hide specific layout of internal data structures(Abstraction)• Add method to Box class
void volume(){System.out.print(“Volume is: ”);;System.out.println(width*height*depth);
}
28/04/2023 BY: Raju Pal 89
Returning a Value
double volume(){return width*height*depth;}
• The type of data returned by a method must be compatible with the return type specified by the method.
• The variable receiving the value returned by a method must also be compatible with the return type specified for the method.
28/04/2023 BY: Raju Pal 90
Parameterized Methodsvoid setDim(double w, double h, double d){width = w;height = h;depth = d;
}
Parameters: variable defined by a method that receives a value when the method is called
Arguments: value that is passed to a method when it is invoked.
28/04/2023 BY: Raju Pal 91
ConstructorsBox(){ //default constructor}Box(){width = 10;height = 10;depth = 10;
}Box(double w, double h, double d){width = w;height = h;depth = d;
}Box myBox = Box();Box yourBox = Box(20,20,20);
• Constructors are a special kind of methods that are invoked to construct objects.
• A Constructor initializes an object immediately upon creation.
• Automatic initialization.
28/04/2023 BY: Raju Pal 92
Constructors cont…• A constructor with no parameters is referred to as a default
constructor.
• Constructors must have the same name as the class itself.
• Constructors do not have a return type—not even void.
• Implicit return type of a class’ constructor is the class type itself.
• Constructors are invoked using the new operator when an object is created.
• Constructors play the role of initializing objects.
28/04/2023 BY: Raju Pal 93
The this Keyword• this can be used inside any method to refer to the current
object.
• When you want to pass the current object to a method.
• To resolve any name space collisions that might occur between instance variables and local variables.Box(double width, double height, double depth){this.width = width;this.height = height;this.depth = depth;
}
28/04/2023 BY: Raju Pal 94
The this Keyword Cont…class Data{
private String data_string;Data(String S){data_string = s;}public String getData(){return data_string;}public void printData(){
Printer p = new Printer();p.print(this);
}}class Printer{
void print(Data d){System.out.println(d.getData);}}public class app{
public static void main(String args[]){
(new Data(“Hello from Java”)).printData();}
}
28/04/2023 BY: Raju Pal 95
Overloading Methods• Method overloading defines several different versions of a method
all with the same name, but each with a different parameter list.
• At the time of method call, java compiler will know which one you mean by the number and/or types of the parameters.
• Overloaded methods must differ in the type and/or number of their parameters.
• Implements polymorphism
• May have different return types.
• To overload a method, you just define it more than once, specifying a new parameter list different from every other
28/04/2023 BY: Raju Pal 96
Overloading Methods exampleClass calculator{int add(int op1, int op2){return op1+op2;}int add(int op1, int op2, op3){return op1+op2+op3;}
} In C you have three functions to get the absolute value of different data types–
abs() for integer, fabs() for floating point, and lfabs() for long integer.
28/04/2023 BY: Raju Pal 97
Overloading Constructors• Works like overloading other methods.
• Define the constructor a number of times, each time with a different parameter list.
//when all dimensions specifiedBox(double w, double h, double d){Width = w;Height = h;Depth = d;
}//when cube is createdBox(double l){Width = Height = Depth = l;
}
Box myBox = new Box(10,20,15);Box yourBox = new Box(25);
28/04/2023 BY: Raju Pal 98
Using Objects as Parameters• An object of a class can be passed as parameter to both methods and
constructors of a class./*construct a new object so that it is initially the same as some existing object.
Define a new constructor Box that takes an object of its class as a parameter.
*/Box(Box ob){Width = ob.Width;Height = ob.Height;Depth = ob.Depth;
}Box myBox = new Box(10,20,15);Box yourBox = new Box(myBox);
28/04/2023 BY: Raju Pal 99
Using Objects as Parameters cont…//objects may be passed to methodsclass Test{int a,b;Test(int i, int j){a = i;b = j;}//return true if obj is equal to the invoking obbjectboolean equals(Test obj){if(obj.a == a && obj.b == b) return true;else return false;}
}Test ob1 = new Test(100, 22);Test ob2 = new Test(100, 22);Test ob3 = new Test(-1,-1);ob1.equals(ob2); trueOb1.equals(ob3); false
28/04/2023 BY: Raju Pal 100
Type of Argument Passing Call-by-value:
• When you pass an item of a simple data type to a method.• Method only gets a copy of the data item.• The code in the method cannot affect the original data item at all.
class Test{void meth(int i, int j){i=i*2;j=j/2;}
}
Test ob = new Test();int a = 15, b = 20;Systeem.out.println(“ a and b before call: “ +a+” “+b); 15 20ob.meth(a,b);Systeem.out.println(“ a and b after call: “ +a+” “+b); 15 20
28/04/2023 BY: Raju Pal 101
Type of Argument Passing cont… Call-by-reference:
• When you pass an object to a method.• Java actually passes a reference to the object.• Code in the method can reach the original object.• Any change made to the passed object affect the original object.
class Test{int a,b;Test(int i, int j){a = i;b = j;
}void meth(Test o){o.a = o.a*2;o.b = o.b/2;}
}Test ob = new Test(15,20);Systeem.out.println(“ a and b before call: “ +a+” “+b); 15 20ob.meth(ob);Systeem.out.println(“ a and b after call: “ +a+” “+b); 30 10
28/04/2023 BY: Raju Pal 102
Returning Objects from Methods
• A method can return objects just like other data types.
• The object created by a method will continue to exist as long as
there is a reference to it.
• No need to worry about an object going out-of-scope because
the method in which it was created terminates.
28/04/2023 BY: Raju Pal 103
Returning Objects Exampleclass Test{int a;Test (int i){a = i;}Test incrByTen(){Test temp = new Test(a+10);return temp;}
}Class RetOb{public static void main(String args[]){Test ob1 = new Test(2);Test ob2;ob2 = ob1.incrByTen();System.out.println(“ob1.a: “+ob1.a);System.out.println(“ob2.a: “+ob2.a);}
}ob1.a = 2;ob2.a = 12;
28/04/2023 BY: Raju Pal 104
Visibility Modifiers Accessor Methods
• Visibility modifiers specify which parts of the program may see and use any particular class/method/field.
• How a member can be accessed is determined by the access specifier that modifies its declaration.
• Java has three visibility modifiers: public, private, and protected.
When no access specifier is used , then by default the member of a class is public within its own package but can not be accessed outside its package.(default visibility)
28/04/2023 BY: Raju Pal 105
Visibility Modifiers - Classes• A class can be defined either with the public modifier or
without a visibility modifier (default visibility).
• If a class is declared as public it can be used by any other class
• If a class is declared without a visibility modifier it has a default visibility.
• A member is a field, a method or a constructor of the class.
• Members of a class can be declared as private, protected, public or without a visibility modifier (default):
28/04/2023 BY: Raju Pal 106
Public Visibility• Members that are declared as public can be accessed from any
class that can access the class of the member
• We expose methods that are part of the interface of the class by declaring them as public
• We do not want to reveal the internal representation of the object’s data. So we usually do not declare its state variables as public (encapsulation)
28/04/2023 BY: Raju Pal 107
Private Visibility• A class member that is declared as private, can be accessed only
by code that is within the class of this member.
• We hide the internal implementation of the class by declaring its state variables and auxiliary methods as private.
• Data hiding is essential for encapsulation.
28/04/2023 BY: Raju Pal 108
class Data{public int [] a={0,0,0,0,0,0,0};}class app{public static void main(String args[]){
Data d= new Data();for(int i=0;i<d.a.length;i++)System.out.println(d.a[i]);
}}
class Data{public int [] a={1,0,0,0,0,0,0};}
class app{void print(Data obj){System.out.println(obj.a[0]); }
public static void main(String args[]){
Data d= new Data();app b=new app();b.print(d);for(int i=0;i<d.a.length;i++)System.out.println(d.a[i]);
}}
28/04/2023 BY: Raju Pal 109
class Test {int a; // default accesspublic int b; // public accessprivate int c; // private access// methods to access cvoid setc(int i) { // set c's valuec = i;}
int getc() { // get c's valuereturn c;}}
class AccessTest {public static void main(String args[]) {Test ob = new Test();// These are OK, a and b may be accessed directlyob.a = 10;ob.b = 20;// This is not OK and will cause an error// ob.c = 100; // Error!// You must access c through its methodsob.setc(100); // OKSystem.out.println("a, b, and c: " + ob.a + " " +ob.b + " " + ob.getc());}}
28/04/2023 BY: Raju Pal 110
The static Keyword• Create a member that can be used by itself, without reference to
a specific instance or object.
• A static member can be accessed before any objects of its class are created.
• You can declare both methods and variables to be static.
• These variables are, essentially, global variables.
• No copy of a static variable is made when objects of its class are declared.
• All instances of the class share the same static variables.
28/04/2023 BY: Raju Pal 111
static MethodsMethods 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.
final Keyword
• A variable can be declared as final.
• contents of the variable cannot can not be modified.
• Must initialize a final variable when it is declared.
– Final int a=10;
– Final flaot = 10.45f
28/04/2023 BY: Raju Pal 112
// Demonstrate static variables, methods, and blocks.class UseStatic{static int a = 3;static int b;static void meth(int x) {System.out.println("x = " + x);System.out.println("a = " + a);System.out.println("b = " + b);}static {System.out.println("Static block initialized.");b = a * 4;}public static void main(String args[]) {meth(42);}}
Output:Static block initialized.x = 42a = 3b = 12
28/04/2023 BY: Raju Pal 113
class StaticDemo {static int a = 42;static int b = 99;static void callme() {System.out.println("a = " + a);}
class StaticByName {public static void main(String args[]) {StaticDemo.callme();System.out.println("b = " + StaticDemo.b);}}
Output:a = 42b = 99
28/04/2023 BY: Raju Pal 114
Exploring the String Class• every string you create is actually an object of type String.
Even string constants are actually String objects.System.out.println("This is a String, too");the string “This is a String, too” is a String constant.
• objects of type String are immutable; once a String object is created, its contents cannot be altered
• If you need to change a string, you can always create a new one that contains the modifications.
• Java defines a peer class of String, called StringBuffer, which allows strings to be altered, so all of the normal string manipulations are still available in Java.
28/04/2023 BY: Raju Pal 115
// Demonstrating Strings.class StringDemo {public static void main(String args[]) {String strOb1 = "First String";String strOb2 = "Second String";String strOb3 = strOb1 + " and " + strOb2;System.out.println(strOb1);System.out.println(strOb2);System.out.println(strOb3);}}
Methods of String Class
Javap java.lang.String
boolean equals(String object)int length( )char charAt(int index)
28/04/2023 BY: Raju Pal 116
// Demonstrate String arrays.class StringDemo3 {public static void main(String args[]) {String str[] = { "one", "two", "three" };for(int i=0; i<str.length; i++)System.out.println("str[" + i + "]: " +str[i]);}}
28/04/2023 BY: Raju Pal 117
Using Command-Line Arguments// Display all command-line arguments.class CommandLine {public static void main(String args[]) {for(int i=0; i<args.length; i++)System.out.println("args[" + i + "]: " +args[i]);}}
java CommandLine this is a test 100 -1
args[0]: thisargs[1]: isargs[2]: aargs[3]: testargs[4]: 100args[5]: -1
28/04/2023 BY: Raju Pal 118
Taking Input from Userimport java.io.*;class StringDemo {public static void main(String args[]) throws IOException{System.out.println("Enter");BufferedReader br=new BufferedReader(new InputStreamReader(System.in));String A= br.readLine();int a=Integer.parseInt(br.readLine());char c=(char)br.read();System.out.println(a);System.out.println(A);}}
28/04/2023 BY: Raju Pal 119