Sie sind auf Seite 1von 75

1

2
3
4
ER/CORP/CRS/LA06/003 5
6
In Java, there is one more access specifier called default access specifier. There is
no specific keyword to be used and accessibility of default access specifier will be
dealt in detail when package concept is introduced in Day 7.

7
Methods (1 of 4)

 Methods define the behavior of an object

 A method defines an interface to expose the state of an object to


external world

 All the methods should be defined inside the class with an access
specifier

 Values that are passed to methods are know as arguments/parameters

 Value that is returned from a method is known as return value

 A method can return only one value at a time

2009-2011, Infosys Limited. 8 Confidential


Implementation of a method requires the following:

Method Declaration or Method Prototype :


The prototype consists of the return type, name of the method and
arguments if any

Method Definition :
Consists of the functionality to be implemented

Method Invocation / call :


To utilize a methods functionality , the method is called or invoked

9
10
Methods are similar to functions that are written in programming languages like C .
Methods have a return type, name and optional parameters and may have a body.
It is a convention for methods which are used for setting values to member variables
and getting values from member variables. These methods are called setter and
getter methods respectively.
Coding Standards
All programming languages will have certain standards for writing the code.
The coding standards for Java is as follows:
Class Name: Should follow pascal Case
First letter should be Uppercase
First letter of each internal word should be capitalized(if it is
present)
Instance Variable: Should follow Camel Case
First letter should be Lowercase
First letter of each internal word should be capitalized(if it is
present)
Method Name:Should follow Camel Case
First letter should be Lowercase
First letter of each internal word should be capitalized(if it is
present)

11
Variables(instance variables,local variables and reference variables) will be dealt
with in detail in the following slides .
How is abstraction & encapsulation achieved in this code?

Abstraction is the process of identifying the essential details to be


known and the non-essential details which need not be known to the end user. Here
the essentials details to be known are specified using public access specifier and
non-essential details are specified using private access specifier.

Encapsulation hides the internal details and allows a simple interface


which ensures that the object can be used without having to know how it works. The
member variables and methods are bound together in the class Customer. This way
encapsulation is achieved.

12
13
Ans: By Creating objects of Customer class

14
Class is an abstract data type and object is a variable of type class

15
16
What is dynamic memory allocation?

This refers to allocation of memory at run time by the operating environment. Here
the memory will be allocated from the Heap segment.

17
A reference is similar to a pointer to the object. Java however does not allow the
programmers to manipulate the references eg. Does not allow to dereference a
reference to an object.

In C, pointers can be manipulated by the programmer which leads to many memory


related problems and program crashes

18
19
Data members of a class can also be accessed using . operator based on the
accessibility specified using access specifiers

println() is the method in Java to print the data on the system console (monitor). The
usage
syntax of the println() is given in the slides. The details of the syntax is beyond the
scope of this
course

Any code in Java is to be written inside a class since it is a pure Object


Oriented Programming Language. Just like the C language, the program
execution starts with the main method. But in Java, even the main
method should be inside a class and it is called the starter class.

The details of the prototype of the main method will be discussed in due course
later.
Starter class contains the main() method in Java

For your reference only, more details can be read on


http://Java.sun.com/J2SE/1.5.0/docs/tooldocs/windows/java.html

20
Data members of a class can also be accessed using . operator based on the
accessibility specified using access specifiers

println() is the method in Java to print the data on the system console (monitor). The
usage
syntax of the println() is given in the slides. The details of the syntax is beyond the
scope of this
course

Any code in Java is to be written inside a class since it is a pure Object


Oriented Programming Language. Just like the C language, the program
execution starts with the main method. But in Java, even the main
method should be inside a class and it is called the starter class.

The details of the prototype of the main method will be discussed in due course
later.
Starter class contains the main() method in Java

For your reference only, more details can be read on


http://Java.sun.com/J2SE/1.5.0/docs/tooldocs/windows/java.html

21
A Java program file is a text file with . java extension. Java source files
may be created in a
text editor like TextPad

To compile a Java program using TextPad


Go to Tools -> Compile Java or press (Ctrl + 1)

To run Java program using TextPad


Go to Tools -> Run Java Application or press (Ctrl + 2)

A .java file can have any number of classes. If a class contains main method, then
the .java file should be saved using the name of the class which contains the
main method.

22
23
Goals Why Java?
Goals of Java were
Platform Independence
Writing secure network mobile programs
Features in the language leading to robustness
The Java Programming Language
Java was conceived by a team of engineers in Sun Microsystems in 1991 as a part of a research project, which was led by James Gosling and
Patrick Naughton. It took 18 months to develop the first working version. This language was initially called Oak but was renamed as Java
in 1995.Modeled after C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both
at the source and at the binary level, which means that the same Java program can run on any machine
Object Oriented Object-Oriented design is a technique that helps the programmer visualize the program using real-life objects. Ease of use
and Reusability are the other benefits of
Object Orientation. It is a pure object oriented language. Class definitions are mandatory
Programmer Friendly features
Compared to earlier OO languages like C++, it is simpler for the programmer to use the features Designed considering the pitfalls of earlier
languages
Robust
Strong type checking (all data must be declared to belong to an explicit type)
Local variables must be initialized
Two main reasons for program failure are related to: (1) memory management (2) run time errors
(1) Memory management is very easy since the de allocation is done by the garbage collection system automatically (more on this later)
(2) Java provides object oriented exception handling to manage run time errors (covered later in Java stream).
Architecture Neutral / Portable (Write once, Run anywhere)
Java source code is platform independent . In C & C++, the source code is portable , but with the limitation of being recompiled on
different platforms . In Java, the source code need not be recompiled on different Java platforms. Example: Java code compiled on
Windows can be run on Unix without recompilation
Other features include

24
Security
Java programs are network mobile. Hence there is a possibility of the downloaded program harming the system. Java is a secured
programming language because it provides the user with a Virtual Firewall between the applications and the computer thus ensuring that
the data in the users system is protected by any possible infectious contents(like virus). This is achieved by confining the Java program
within the Java Runtime Environment.
Multithreaded
Multithreading is the capability of a program to perform several tasks simultaneously within a program. These tasks are independent of each
other. A good example of multithreading would be one of the game software where the GUI display, sound effect, timer control and score
updating are happening within the same process simultaneously. In network programming, a server can serve multiple clients at the same
time via mutithreading. Java is used on networks and hence supports this feature to help optimize performance on the network
Dynamic
Java loads classes as and when required and hence machine code size includes only the source code written. This makes it possible to
dynamically link code in a safe manner
The Java Byte Code
Refer back to the Compiler concepts discussed on Day 6 of Programming Basics course. (Compiler techniques in graduation college) Byte
code is the intermediate code generated when a Java source file (.java) is compiled. This byte code is the input to the Java Virtual
Machine.Byte codes have the extension .class, hence called the Java class file. When a C/C++ program is compiled, an executable
binary file is created which is specific to the target hardware and operating system because it contains machine language specific to
target processor. Hence these programs need to be recompiled on each platform. In contrast, the Java byte code is not specific to the
target platform and hence with the support of JVM it can be run anywhere without recompilation. Hence, it facilitates Write Once,
Run Anywhere
The Java Virtual Machine
JVM interprets the byte code into the machine language format of the platform on which it is running. JVM is not a real machine, it is just a
virtual machine. The JVM contains a class loader and an execution engine. The class loader loads the byte code and the execution engine
interprets the byte code.
JVM is platform dependant ie. there is one JVM for Windows another one for UNIX, yet another one for Mainframe etc.
Platform independence in Java is achieved with the help of byte codes and JVM. Byte codes are platform independent and hence need not be
recompiled on any platform provided the platform has the corresponding JVM.
The JVMs for all platforms are available free (http://java.sun.com/) and hence we say that the byte code runs in all platforms
Figure shows that Java programs can be written and compiled to byte codes which can be ported to any platform, but the JVM
is specific to th
e platform . The byte codes are interpreted by the JVM

25
26
Whenever an object is created, memory will be allocated for the instance variables
also. They will be stored in the heap memory along with the object to which they
belong

Note: Here it is assumed that reference variable declaration is done inside the
main() method, hence will be treated as a local variable and memory will be
allocated in the stack

27
Note: Here it is assumed that reference variable declaration is done inside the
main() method, hence will be treated as a local variable and memory will be
allocated in the stack

How many objects and reference variables are created ?

2 reference variables, custObj1 and custObj2 &


1 object

28
29
Garbage Collection
In the Java programming language, the dynamic allocation of objects is achieved
using the new operator. An object once created uses some memory and the memory
remains allocated till there are references for the use of the object. When there are
no references for an object, it is assumed to be no longer needed and the memory
occupied by the object can be reclaimed. There is no explicit need to destroy an
object as java handles the de-allocation automatically. The technique that
accomplishes this is known as Garbage Collection.

Programs that do not de-allocate memory can eventually crash when there is no
memory left on the system to allocate. These programs are said to have memory
leaks. Memory leak is a common problem in C and C++ languages where memory
dynamically allotted is not freed

30
Note: Here it is assumed that reference variable declaration is done inside the
main() method, hence will be treated as a local variable and memory will be
allocated in the stack

31
Note: Here it is assumed that reference variable declaration is done inside the
main() method, hence will be treated as a local variable and memory will be
allocated in the stack

32
Note: Here it is assumed that reference variable declaration is done inside the
main() method, hence will be treated as a local variable and memory will be
allocated in the stack

33
34
Naming Conventions
Variable names should be short yet meaningful
One-character variable names should be avoided except for temporary
"throwaway" variables
It is automatically created when the method is invoked and destroyed when the
method is exited hence local, automatic and temporary variable
Local variables are stored in the stack memory and hence the name stack variable
Access specifiers are not used with local variables
Local variables(both built in and class type) are stored in stack

35
36
37
Values can be passed to a method either using

Pass by Value

Pass by Reference

Objects are always passed by reference

Comparing the customerId values of the two customer objects in a validateCustomerId()


can be done in the following way also :

public void validateCustomerId(Customer obj1,Customer obj2){


if(obj1.getCustomerId()==obj2.getCustomerId()){
System.out.println("Same Customer Ids");
}
else{
System.out.println("Different Customer Ids");
}
}

38
Values can be passed to a method either using

Pass by Value

Pass by Reference

Objects are always passed by reference

Comparing the customerId values of the two customer objects in a validateCustomerId()


can be done in the following way also :

public void validateCustomerId(Customer obj1,Customer obj2){


if(obj1.getCustomerId()==obj2.getCustomerId()){
System.out.println("Same Customer Ids");
}
else{
System.out.println("Different Customer Ids");
}
}

39
40
In a class if the name of an instance variable is same as the local variable of a
method then inside the method local variable hides the instance variable. This
phenomena is known as instance variable hiding

41
42
Q1. Ans
1 C, 2 - A, 3 B
Q2. Ans
No. of Reference Variables = 3
No. of Objects = 1

43
Q3. Ans
myVariable Heap
temp Stack
obj - Stack

44
45
46
Note: In Java, % can be applied to floating-point data type also unlike C

47
48
In case of
Short Circuit AND (&&), If the first expression is false second
expression will not get evaluated
Short Circuit OR (||), If the first expression is true second expression
will not get evaluated

Recollect logical operators discussed as part of Programming Basics / Programming


Practices module

49
50
<statement_or_block>* : In this statement * represent any number of
statements or block

51
52
53
54
55
56
Recollect the same concept discussed in Programming Basics Course. In Java, unlike C there is
strong type checking and any narrowing conversion will result in a compilation error. In C, there will
not be any compilation error.

A variable of one type can receive the value of another type when,

The data type of the variable receiving data is wider than the data type of the variable from
which it is receiving data, provided the data types are compatible

The data type of the variable receiving data is narrower than the data type of the variable
from which it is receiving data, provided the data types are compatible

57
Widening Conversion
The data type of the variable receiving data is wider than the data type of the variable from which it is receiving
data, provided the data types are compatible

Narrowing Conversion
The data type of the variable receiving data is narrower than the data type of the variable from which it is
receiving data, provided the data types are compatible

Java has a strong type checking. In case of Narrowing conversion there is a possibility of loss of data.
Such type of conversion is not allowed directly but can be done with explicit casting
In case of C language, such type conversions are allowed. Hence we say that C language does not
have strong type checking

58
Type Casting
In some cases, the system implicitly changes the type of an variable without your explicitly performing a
cast. You can explicitly change the type of a value by casting. The process of assigning a value of variable
to a variable of another type is called casting.

Automatic, non-explicit type changing is known as Conversion. If the data types of the two variables
involved in the conversion are compatible, then Java does the conversion automatically. If the data types
are not same, then a cast must be done explicitly.
Note: boolean data cannot be converted to any other data type and vice-versa
E.g.:
An int value can be assigned to a long variable but there is no conversion defined from float to byte.
CastingExample.java
// TYPE CASTING
class CastingExample
{ public static void main(String args[])
{ byte x;
int a=270;
double b =128.128;
System.out.println("\n int converted to byte");
x=(byte) a;
System.out.println("a and x "+ a +" "+x);
System.out.println("\n double converted to int");
a=(int) b;
System.out.println("b and a "+ b +" "+a);
System.out.println("\n double converted to byte");
x=(byte) b;
System.out.println("b and x "+b +" "+x);
}
} 59
In C programming language, there are many implicit conversions which may lead to loss of data which is
60
Is there a loss of data, if so Why?

Ans: Yes, there is loss of data even though we have done Type casting. This is
because totalCharges is considered as int.
This means by doing Type Casting loss of data cannot be prevented but the strong
type checking will prevent accidental loss of data

61
62
Q4. Ans
varThree:20.0
Since 7/100 (integer division) results in 0, although there is type
casting, there is loss of data

63
Q5. Ans
varThree:90.0

64
Q6. Ans
varThree:20.0

65
Note: there are 2 errors in the code

66
Q8. Ans
Data is valid

67
Q9. Ans
Your Ticket Fare is 40.0

68
Q10. Ans
Compilation Error: Trying to access a private instance variable
directly using reference variable name

69
Q11. Ans
PIN: 570020

70
71
72
The class diagram for the complete retail store application is shown above. In Day
2, we have learnt about the member variables and member methods of a
classs. control structures and operators.

73
74
75

Das könnte Ihnen auch gefallen