Introduction To Java
Introduction To Java
Importance and Features of Java Constants Variables Data Types Operators and Expressions Decision Making Branching : If-Else, Switch, Conditional Operator (? :) Looping : While, Do, For Statements Introducing classes Objects and Methods: Defining a Class Adding Variables and Methods Creating Objects Constructors Access Protection
Gaurav Gotra@ CDAC Noida 2
Javas Lineage
From C, Java derives its syntax.
Many of Javas Object-Oriented features influenced by C++.
Structured Vs OOP
Structured Focuses on Process Follows Top Down Approach OOP Focuses on Object Follows Bottom Up Approach
10
Java Architecture Java stores source code files as ASCII text files. Java source files are later compiled to Byte-code files. Byte-code is a standardized, machine independent, low level language. The byte-code files are loaded and interpreted at the clients machine by a special program called the Java Virtual machine (JVM).
11
The Java Virtual Machine (JVM) The client application or operating system must have a Java byte-code interpreter to execute larger programs, this is called the JVM. The JVM, interprets the byte-codes into native code and is available on platforms that supports java.
When a browser invokes the JVM to run a Java program , the JVM does a number of things: It validates the requested byte-codes , verifying that they pass various formatting and security checks. This is a security feature known as the byte-code verifier . It allocates memory for the incoming Java class files and guarantees that the security of JVM is not violated. This is known as the class loader. It interprets the byte-code instructions found in the class files to execute the program.
Gaurav Gotra@ CDAC Noida 12
The figure below illustrates how the components of JVM work together when a Java Applet is requested over the network from a web browser.
Bytecode (.Class files) Web Browser JVM Bytecode verifier class loader Java JIT compiler
13
Java Features
Simple Secure Portable Object Oriented Robust Memory Management and Mishandled Exceptional Condition Multithreaded Write programs that do many things simultaneously Architecture Neutral Interpreted Cross Platform High Performance Byte Code runs faster as pre compiled Distributed RMI (Remote Method Invocation) Dynamic Run Time Information that is used to verify and resolve
accesses to objects at Run Time
Gaurav Gotra@ CDAC Noida 14
15
Encapsulation
The process of bringing together the data and method of an object is called as encapsulation The data and method are given in the class definition Classes provides us with this feature Encapsulation
16
What is Inheritance?
Classes inherit state and behavior from their superclass. Inheritance provides a very helpful concept of code reusability.
Hierarchy of Classes
Gaurav Gotra@ CDAC Noida 17
Polymorphism Polymorphism may be defined as the ability of related objects to respond to the same message with different, but appropriate, actions.
Shape Draw ( )
Polymorphism
Gaurav Gotra@ CDAC Noida 18
Overloading In Object Oriented Programming if a method depending on some information does different job at different times that method is overloaded .Overloading is nothing but a kind of polymorphism.
19
Example:
20
Overriding Inheritance is a mechanism of inheriting the traits of parents but some times some properties should be modified according to the need like a son inherits legs from his parents but his walking style is different. This is Overriding. It is again a kind of polymorphism and very important in terms of dynamic decisions.
Benefits of OOP
Through inheritance, we can eliminate redundant code and extend the use of existing classes.
21
The figure below illustrates the process by which Java source code files are compiled and interpreted.
Source Code (Java files)
Standalone Application
Java.exe
22
24
25
Example
public class varconstltr { public static final int constint=5; }
26
The necessary requirements for making a running program are: The path of the jdk1.5/bin should be present. The Name of the file in which the program is stored should be the same as the name of the class in which the main method is present( with .java extension).
In Java, there are really two different categories in which data types have been divided:
Java has 8 primitive data types built into the Java language
Reserved Word byte short int long float double char boolean Data Type Byte-length integer Short integer Integer Long integers Single precision number Real number with double precision Character (16-bit Unicode) Has value true or false Size 1 byte 2 bytes 4 bytes 8 bytes 4 bytes 8 bytes 2 bytes A Boolean Value Range of Values
Identifiers in Java Identifiers are the names of variables, methods, classes, packages and interfaces. Identifiers must be composed of underscore _ and the dollar sign $. letters, numbers, the
MyVariable is not the same as myVariable. There is no limit to the length of a Java variable name.
Gaurav Gotra@ CDAC Noida 28
The following are valid variable names: MyVariable myvariable MYVARIABLE x i _myvariable $myvariable _9pins
The following are invalid variable names. My Variable // Contains a space 9pins // Begins with a digit a+c // The plus sign testing1-2-3 // The hyphen Character Variables They can be treated as either a 16-bit unsigned integer with a value from 0-65535, or as a Unicode character. The Unicode standard makes room for the use of alphabets of many different languages'. The Latin alphabet, numerals, and punctuation have the same values as the ASCII character set (a set that is used on most PCs and have values between 0-256). The default value for a char variable is \u0000.
30
The syntax to create a character variable is the same as for integers and Booleans: char myChar = b; In this example, the myChar variable has been assigned the value of the letter `b'. Notice the single quote around the letter b? These tell the compiler that you want the literal value of b rather than an identifier called b. Integer Variables
The following lines show how to create variables of integer types: byte My_First_Byte = 10; short My_First_Short = 15; int My_First_Int = 20; long My_First_Long = 25;
Gaurav Gotra@ CDAC Noida 31
Boolean Variables A Boolean variable is not a number. It can have one of two values: true or false. There are two ways to set its values. The first way to do this is explicitly. For instance, if you have a variable called My_First_Boolean, to change this variable to false you would type:
My_First_Boolean = false;
The second way to assign a Boolean variable is based on an equation or other variable. For instance, if you wanted My_First_Boolean to have the same value as on_the_table, you might type a line like this: My_First_Boolean= on_the_table;
You can also make the variable have a value based on the equality of other numbers. For instance the following line would make My_First_Boolean false:
Gaurav Gotra@ CDAC Noida 32
My_First_Boolean = 6>7; Because 6 is not greater than 7, the equation on the right would evaluate to false. Float Variables In Java, floating-point numbers are represented by the types float and double. Both of these follow a standard floating point specification: IEEE Standard for Binary Floating-Point Arithmetic, ANSI/IEEE Std. 754-1985 (IEEE, New York). The fact that these floating-point numbers follow this specification--no matter which machine the application or applet is running on--is one of the details that makes Java so portable.
33
Double
4.94065645841246544e-324d 01.7976931348623157e+308d
(Minimum) (Maximum)
In addition, there are three unique states that floating-point numbers can have:
Literals are pieces of Java source code that indicate explicit values. For instance "Hello World!" is a String literal and its meaning is the words Hello World! Java has four kinds of literals.
Gaurav Gotra@ CDAC Noida 34
String Literal
The string literal is always enclosed in double quotes. Java uses a String class to implement strings, whereas C and C++ use an array of characters. For example:
"Hello World!"
String poem = "Mary had a little lamb whose fleece was white as snow and everywhere that Mary went the lamb was sure to go."; Instead you must use \n and the String concatenation operator, +, like this: String poem = "Mary had a little lamb \n" +"whose fleece was white as snow \n" + "and everywhere that Mary went \n" + "the lamb was sure to go.";
Gaurav Gotra@ CDAC Noida 35
Character Literal A backslash is used to denote the non-printing characters such as: Description Line feed Horizontal tab Back slash Single quote Double quote Escape Sequence \n \t \\ \ \
36
Boolean Literal Boolean literal can have either of the values: true or false. They do not correspond to the numeric values 1 and 0 as in C and C++. Numeric Literals
There are two types of numeric literal: integers and floating point numbers. For example:
37
34 is an integer literal and it means the number thirty-four. 1.5 is a floating point literal.
45.6, 76.4E8(76.4 times 10 to the 8th power) and -32.0 are also floating point literals.
Operators
Operators can be broadly categorized as: Relational and Equality operators Relational operators are binary operators that require two operands to work on. The operands can be either constants or variables or expression. The operators are as follows: > >= < <= ! != greater than greater than or equal to less than less than or equal to boolean NOT not equal to Gaurav Gotra@ CDAC Noida
38
Assignment Operators
= ^= &= %= -= *= /= |= >>= <<= >>>= assignment bitwise XOR and assign bitwise AND and assign take remainder and assign subtract and assign multiply and assign divide and assign bitwise OR and assign shift bits right with sign extension and assign shift bits left and assign unsigned bit shift right and assign
39
Bitwise | ^ & >> << ~ >>> bitwise OR bitwise XOR bitwise AND right shift left shift bitwise NOT unsigned bit shift right
Gaurav Gotra@ CDAC Noida 40
++ - && || == ?: !
41
<< >>
Integral Integral
42
Integral Arithmetic Arithmetic Object, type Primitive Primitive Object Object Integral, Boolean Integral, Boolean Integral, Boolean Boolean Boolean
Right shift with zero extension Less than, Less then or equal Greater than, Greater than or equal Type comparison Equal (have identical values) Not equal (have different values) Equal (refer to the same object) Equal (refer to different object) Bitwise AND, Bitwise XOR, Bitwise OR, Conditional AND Conditional OR
43
Keywords
Keywords are identifiers like public, static and class that have a special meaning inside Java source code and outside of comments and Strings. Keywords are reserved for their intended use and cannot be used by the programmer for variable or method names. Some of the reserved keywords in Java 1.1. are:
44
char class
const
finally float
for
long native
new
strictfp super
switch
volatile while
Note - goto and const are keywords in Java but not used in Code
Gaurav Gotra@ CDAC Noida 45
Separators in Java
Separators help define the structure of your program. The separators used in Java are: Parentheses Braces the period the semicolon Purpose of Operator ( ) Encloses arguments in method definitions and calling; adjusts precedence in arithmetic expressions; surrounds cast types and delimits test expressions in flow control statements. ( ), { }, . ;
46
double fahr, celsius; double lower, upper, step; // lower limit of temperature table lower = 0.0; // upper limit of temperature table
upper = 300.0;
// step size step = 20.0; fahr = lower; while (fahr <= upper) { celsius = (5.0 / 9.0) * (fahr-32.0);
Gaurav Gotra@ CDAC Noida 48
System.out.println(fahr + " " + celsius); fahr = fahr + step; } } } The output is as follows: % java FahrToCelsius.Java % java FahrToCelsius
0.0 -17.77777777777778 20.0 -6.666666666666667 40.0 4.444444444444445 60.0 15.555555555555557 80.0 26.666666666666668 100.0 37.77777777777778
Gaurav Gotra@ CDAC Noida 49
120.0 140.0 160.0 180.0 200.0 220.0 240.0 260.0 280.0 300.0
%
48.88888888888889 60.0 71.11111111111111 82.22222222222223 93.33333333333334 104.44444444444444 115.55555555555556 126.66666666666667 137.77777777777777 148.88888888888889
50
Mixing Data Types Besides combining different operations, you can mix and match different numeric data types on the same line. The program below uses both ints and doubles, for example.
class IntAndDouble { public static void main (String args[]) { int i = 10; double x = 2.5; double k; System.out.println("i is " + i); System.out.println("x is " + x); k = i + x; System.out.println("i + x is " + k); k = i * x;
Gaurav Gotra@ CDAC Noida 51
x is " + k);
- x is " + k);
- i is " + k);
/ x is " + k); / i is " + k);
52
i x i i i x i x
53
Type Casting For instance: int i = (int) 9.0/4.0; Converting Strings to Numbers To convert the String "22" into the int 22 you would write int i = Integer.valueOf("22").intValue(); Doubles, floats and longs are converted similarly. To convert a String like "22" into the long value 22 you would write long l = Long.valueOf("22").longValue(); To convert "22.5" into a float or a double you would write:
The various valueOf() methods are relatively intelligent and can handle plus and minus signs, exponents, and most other common number formats. However if you pass one of these methods something completely non-numeric like "pretty in pink," it will throw a NumberFormatException. You can now write a program to accept mass in kilograms as user input from the command line.
Here's the output: % javac Mc2.java % java Mc2 0.0456 4.09853e+15 Joules %
56
Unicode
Unicode is a two-byte character code set that has characters representing almost all characters in almost all human alphabets and writing systems around the world including English, Arabic, Chinese and more. You can refer to a particular Unicode character by using the escape sequence \u followed by a four digit hexadecimal number. For example:
\u00AE \u0022 \u00BD \u0394 \u00F8A The copyright symbol " The double quote 1/2 The fraction 1/2 D The capital Greek letter delta little o with a slash through it
Expressions
An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value
Examples : 1*2*3 (x + y) / 100 x + (y / 100)
58
Arrays There are three types of reference variables: Classes Interfaces Arrays
An array is simply a collections of similar items. If you have data that can be easily indexed, arrays are the perfect means to represent them. For instance, if you have five people in a class and you want to represent all of their IQs, an array would work perfectly. An example of such an array is:
int IQ[] = {123,109,156,142,131}; The next line shows an example of accessing the IQ of the third individual: int ThirdPerson = IQ[3];
Gaurav Gotra@ CDAC Noida 59
Arrays in Java are somewhat tricky. This is mostly because, unlike most other languages, there are really three steps to filling out an array, rather than one:
Declare the array: There are two ways to do this: place a pair of brackets after the variable type, or place brackets after the identifier name. The following two lines produce the same result:
Place data in the array. For arrays of native types (like those in this chapter), the array values are all set to 0 initially. The next line shows how to set the fifth element in the array:
MyIntArray[4] = 467;
There are several additional points about arrays you need to know:
Indexing of arrays starts with 0 (as in C and C++). In other words, the first element of an array is MyArray[0], not MyArray[1].
61
Declaring Arrays
Array declarations are composed of the following parts: Array modifiers : (optional) the keywords public, protected, private. Type name: (required) The name of the type or class being arrayed. Brackets (required) [ ] Initialization: (optional) Semicolon (required)
62
Creating Arrays
When you create an array, you must tell the compiler how many components will be stored in it. Here's how you'd create the variables declared on the previous page: k = new int[3]; yt = new float[7]; names = new String[50]; Initializing Arrays
Subscripts are consecutive integers beginning with 0. Thus the array k above has components k[0], k[1], and k[2]. Since you start counting at zero there is no k[3], and trying to access it will throw an ArrayIndexOutOfBoundsException.
Gaurav Gotra@ CDAC Noida 64
For example this is how you'd store values in the arrays above:
k[0] = 2; k[1] = 5; k[2] = -2; yt[17] = 3.5f; names[4] = "Fred"; For even medium sized arrays, it's unwieldy to specify each component individually. It is often helpful to use for loops to initialize the array. Here is a loop which fills an array with the squares of the numbers from 0 to 100. float[] squares; squares = new float[101]; for (int i=0, i <= 100; i++) { squares[i] = i*i; }
Gaurav Gotra@ CDAC Noida 65
Although i is an int, it is promoted to a float when it is stored in squares, since squares is declared to be an array of floats. Examples of Declaring and Initializing Arrays long Primes[] = new long[1000000]; // Declare an array and assign // some memory to hold it. long[] EvenPrimes = new long[1]; // Either way, it's an array. // Now declare an array with an implied `new' and populate. long Fibonacci[] = {1,1,2,3,5,8,13,21,34,55,89,144};
66
long Perfects[] = {6, 28}; // Creates two element array. long BlackFlyNum[];// Declare an array. // Default value is null. BlackFlyNum = new long[2147483647];// Array indexes must be type int. // Declare a two dimensional array and populate it. long TowerOfHanoi[][]={{10,9,8,7,6,5,4,3,2,1},{},{}} ; long[][][] ThreeDTicTacToe;// Uninitialized 3D array.
Gaurav Gotra@ CDAC Noida 67
Decision Making Branching: If-Else, Switch, Conditional Operator (? :) Looping : While, Do, For Statements.
(21-Aug-2012)
68
The if statement in Java You can access the length of an array by using the length static variable as arrayname. length. You can therefore test the length of the args array as follows: // This is the Hello program in Java
class Hello { public static void main (String args[]) { int a =10; if (a > 0){
System.out.println("Hello "); } } } Gaurav Gotra@ CDAC Noida
70
In Java, numerical greater than and lesser than tests are done with the > and < operators respectively. You can test whether a number is (less than or equal to) or (greater than or equal to) another number with the <= and >= operators.
71
There is one way you can still get into trouble: boolean b = true; if(b=false) { System.out.println("b is false"); } To avoid this, some programmers get in the habit of writing condition tests like this: boolean b = true; if (false=b) { System.out.println("b is false"); } Since you can't assign to a literal, this causes a compiler error if you misuse the = sign when you mean to write ==.
Gaurav Gotra@ CDAC Noida 72
// This is the Hello program in Java class Hello { public static void main (String args[]) { int i; System.out.print("Hello "); // Say Hello i = 0;// Initialize loop counter while (i <) { // Test and Loop
73
System.out.print(); System.out.print(" "); i = i + 1; // Increment Loop Counter } System.out.println();// Finish the line } The for loop in Java // This is the Hello program in Java class Hello { public static void main (String args[]) { System.out.print("Hello "); // Say Hello for (int i = 0; i <10; i = i + 1) { // Test and Loop
Gaurav Gotra@ CDAC Noida 74
You can't, however, include multiple test conditions, at least not with commas. The following line is illegal and will generate a compiler error. for (int i=1,j=100;i<=100, j>0;i=i-1, j=j-1) {
To include multiple tests you need to use the boolean logic operators && and || which will be discussed later.
The Do While loop in Java
do { if (i==-1) System.out.print("Hello "); else { System.out.print(); System.out.print(" "); } i = i + 1; } while (i < 10); System.out.println();// Finish the line } }
76
Testing Objects for Equality class JackAndJill { public static void main(String args[]) { String s1 = new String("Jack went up the hill."); String s2 = new String("Jack went up the hill."); if ( s1 == s2 ) { System.out.println("The strings are the same."); } else if ( s1 != s2 ) { System.out.println("The strings are not the same."); } } }
Gaurav Gotra@ CDAC Noida 77
A break statement exits a loop before an entry condition fails. In the example shown below, an error message is printed, and you break out of the for loop if j becomes negative. class CountWheat{ public static void main (String args[]) { int i, j, k; j = 1; k = 0;
78
for (i=1; i <= 64; i++) { j *= 2; if (j <= 0) { System.out.println("Error: Overflow"); break; } k += j; System.out.print(k + "\t"); if (i%4 == 0) System.out.println(); } System.out.println("All done!");
} }
Gaurav Gotra@ CDAC Noida 79
80
Continue
for (int i = 0; i < m.length; i++) { if (m[i] % 2 == 0) continue; // process odd elements... } The continue statement is rarely used in practice, perhaps because most of the instances where it's useful have simpler implementations. For instance, the above fragment could equally well have been written as: for (int i = 0; i < m.length; i++) { if (m[i] % 2 != 0) {; // process odd elements... }}
Gaurav Gotra@ CDAC Noida 81
Labeled Loops Normally inside nested loops break and continue exit the innermost enclosing loop. For example consider the following loops. for (int i=1; i < 10; i++) { for (int j=1; j < 4; j++) { if (j == 2) break; System.out.println(i + ", " + j); } }
83
84
because you break out of the innermost loop when j is two. However the outermost loop continues. To break out of both loops, label the outermost loop and indicate that label in the break statement like this: iloop: for (int i=1; i < 3; i++) { for (int j=1; j < 4; j++) { if (j == 2) break iloop; System.out.println(i + ", " + j); } }
Switch statements are shorthands for a certain kind of if statement. It is not uncommon to see a stack of if statements all relate to the same quantity like this: if (x == 0) do something; else if (x == 1) do something else if (x == 2) do something else if (x == 3) do something else if (x == 4) do something else do something else; else; else; else; else;
86
Java has a shorthand for these types of multiple if statements, the switch-case statement. Here's how you'd write the above using a switch-case: switch (x) { case 0: do something; break; case 1: do something; break; case 2: do something; break; case 3: do something; break; default: do something else; }
Gaurav Gotra@ CDAC Noida 87
The "?:" operator evaluates an expression which may also be an operand and returns operand1 if the expression is true; otherwise returns operand2, if the expression is false. The diagram better explains this
88
if (a > b) { max = a; } else { max = b; } Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
89
Introducing Classes, Objects and Methods, Defining a Class, Adding Variables and Methods, Creating Objects
(23-Aug-2012)
90
What are Classes? A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind.
A Class
Gaurav Gotra@ CDAC Noida 91
92
A Simple Class
class Box { double width; double height; double depth; }
93
What is an Object? Objects are software bundles of data and related procedures. The following illustration is a common visual representation of a software object:
An Object
Gaurav Gotra@ CDAC Noida 94
In the real world its obvious that classes are not themselves the objects that they describe.
Then also occurs because many people use the term object inconsistently and use it to refer to both classes and instances.
The main difference between a class and an object is that objects are tangible, but a class is always intangible. You cant see a class but you can always see an object.
The Benefits of Classes Objects provide the benefit of modularity and information hiding. Classes provide the benefit of reusability
95
Declaring Objects
Box mybox = new Box();
This statement combines the two steps just described. It can be rewritten like this to show each step more clearly:
Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object
96
97
Box b1 = new Box(); Box b2 = b1; // ... b1 = null; Here, b1 has been set to null, but b2 still points to the original object.
Gaurav Gotra@ CDAC Noida 99
Introducing Methods
This is the general form of a method type name(parameter-list) { // body of method }
100
101
class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1.volume(); // display volume of second box mybox2.volume(); } } Gaurav Gotra@ CDAC Noida
102
Output
Volume is 3000.0 Volume is 162.0
103
Returning a Value
// Now, volume() returns the volume of a box. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } }
104
class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } Gaurav Gotra@ CDAC Noida }
105
106
// This program uses a parameterized method. class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) { width = w; height = h; depth = d; } }
107
class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
108
Overloading Methods
// Automatic type conversions apply to overloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter void test(double a) { System.out.println("Inside test(double) a: " + a); } } Gaurav Gotra@ CDAC Noida
109
class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double) } }
Output:
No parameters a and b: 10 20 Inside test(double) a: 88 Inside test(double) a: 123.2
Gaurav Gotra@ CDAC Noida 110
111
call-by-value
// Simple types are passed by value. class Test { void meth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " +a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } Gaurav Gotra@ CDAC Noida 112 }
Output
a and b before call: 15 20 a and b after call: 15 20
113
call-by-reference
// Objects are passed by reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2; o.b /= 2; } }
Gaurav Gotra@ CDAC Noida 114
class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } }
Output
ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10
Gaurav Gotra@ CDAC Noida 115
Returning Objects
A method can return any type of data, including class types that you create. For example, in the following program, the incrByTen( ) method returns an object in which the value of a is ten greater than it is in the invoking object. As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference to it is returned to the calling routine. The preceding program makes another important point: Since all objects are dynamically allocated using new, you dont need to worry about an object going out-of-scope because the method in which it was created terminates. The object will continue to exist as long as there is a reference to it somewhere in your program. When there are no references to it, the object will be reclaimed the next time garbage collection takes place.
116
// Returning an object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } }
117
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); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: " + ob2.a); } }
118
119
Recursion
Recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive.
// A simple example of recursion. class Factorial { // this is a recursive function int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result; } }
Gaurav Gotra@ CDAC Noida 120
class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } }
Output
Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120
121
122
Constructor
Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a 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 immediately after the object is created, before the new operator completes. Constructors look a little strange because they have no return type, not even void. This is because the implicit return type of a class constructor is the class type itself. It is the constructors job to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object immediately.
123
/* Here, Box uses a constructor to initialize the dimensions of a box. */ class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } }
Gaurav Gotra@ CDAC Noida 124
class BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
125
126
Parameterized Constructor
While the Box( ) constructor in the preceding example does initialize a Box object, it is not very usefulall boxes have the same dimensions. What is needed is a way to construct Box objects of various dimensions. The easy solution is to add parameters to the constructor.
127
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */ class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } }
Gaurav Gotra@ CDAC Noida 128
class BoxDemo7 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
129
130
131
Constructor Overloading
In addition to overloading normal methods, you can also overload constructor methods. class Box { double width, height, depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; height = -1; depth = -1; }
Gaurav Gotra@ CDAC Noida 132
// constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; }
133
class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } }
Gaurav Gotra@ CDAC Noida 134
Output Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0
135
Constructor needs to have the same name as that of the class whereas methods need not be the same.
There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value. There is no return statement in the body of the constructor. The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the super class constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameter less super class constructor.
Gaurav Gotra@ CDAC Noida 136
Access Protection
Encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse Java addresses four categories of visibility for class members: Subclasses in the same package Non-subclasses in the same package Subclasses in different packages Classes that are neither in the same package nor subclasses.
Gaurav Gotra@ CDAC Noida 137
No
No No No
Yes
Yes No No
Yes
Yes Yes No
Yes
Yes Yes Yes
138
Access Modifiers
private protected default public
139
141
Example
/* This program demonstrates the difference between public and private.*/ class Test { int a; // default access public int b; // public access private int c; // private access // methods to access c void setc(int i) // set c's value { c = i; } int getc() // get c's value { return c; } }
Gaurav Gotra@ CDAC Noida 142
class AccessTest { public static void main(String args[]) { Test ob = new Test(); // These are OK, a and b may be accessed directly ob.a = 10; ob.b = 20; // This is not OK and will cause an error // ob.c = 100; // Error! // You must access c through its methods ob.setc(100); // OK System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
143
Other Topics
(28-Aug-2012)
144
Garbage Collection
It is a technique that accomplishes deallocation of memory automatically. Since the objects are dynamically allocated by using the new operator, the technique of garbage collection manages the memory for later reallocation. 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.
145
The super key word refers to the superclass of the class in which the keyword is used. It is used to refer to the member variables or the methods of the superclass. class Base{ public void print(){ System.out.println("I Superclass"); } } public class Derived extends Base{ public void printSuper(){ super.print(); //It will call the print() function of superclass (Base) }
Gaurav Gotra@ CDAC Noida 146
am
public void print(){ System.out.println("I am Derived class"); } public static void main(String s[]){ Derived d=new Derived(); d.printSuper(); d.print(); } } At console you do : javac Derived.java java Derived I am Superclass I am Derived class
Gaurav Gotra@ CDAC Noida 147
class Student{ public void print(){ System.out.println("I am a student"); } } class Firstyear_stu extends Student{ public void print(){ System.out.println("I am a first year student"); } } class Secondyear_stu extends Student{ public void print(){ System.out.println("I am a second
Gaurav Gotra@ CDAC Noida 148
year student"); }
} public class Identification { public void identify (Student s){ if(s instanceof Firstyear_stu){//here any decision depending up on the type of object can //be taken s.print(); System.out.println("Assign roll no in the range 1000 to 2000"); } if(s instanceof Secondyear_stu){ s.print(); System.out.println("Assign roll no in the range 2000 to 3000"); } }
Gaurav Gotra@ CDAC Noida 149
public static void main(String s[]){ Firstyear_stu fs=new Firstyear_stu(); Secondyear_stu ss=new Secondyear_stu(); Identification id=new Identification(); id.identify(fs); id.identify(ss); } } At the console you do: javac Identification.java java Identification I am a first year student Assign roll no in the range 1000 to 2000 I am a second year student Assign roll no in the range 2000 to 3000
Gaurav Gotra@ CDAC Noida 150
Understanding static
Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. 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. (The keyword super relates to inheritance and is described in the next chapter.) If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
Gaurav Gotra@ CDAC Noida 151
// 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); } }
Gaurav Gotra@ CDAC Noida
152
Outside of the class in which they are defined, static methods and variables can be used independently of any object. To do so, you need only specify the name of their class followed by the dot operator. For example, if you wish to call a static method from outside its class, you can do so using the following general form classname.method( )
153
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 = 42 b = 99
Gaurav Gotra@ CDAC Noida 154
155
class SubString extends String{} Compiler will say, Cant subclass final classes. The idea is some classes (which will be marked as final) are so specific that they should not be modified even by extending them. A final variable may not be modified once it has been assign to a value. In java, final variables play the same role as const in C++ and #define constants in C. A final method can not be overridden. For example the following code will give compiler error. class Polygon{ Public final void draw(){ //drawing code} } class Rectangle extends Polygon{
Gaurav Gotra@ CDAC Noida 156
157
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 anywhere a reference to an object of the current class type is permitted.
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 window 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. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. 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 those actions that must be performed before an object is destroyed. The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the Java run time calls the finalize( ) method on the object.
Gaurav Gotra@ CDAC Noida 159
The finalize( ) method has this general form: protected void finalize( ) { // finalization code here } Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. 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 whenor even iffinalize( ) 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.
160
Inner Classes
A class that is declared and defined inside some other class is inner class
public class Outer{ int i=10; public class Inner{ int j=20;
161
is
"+ j);
} public void outerFn(){ System.out.println("i is "+ i); } public static void main(String s[]){ Outer out =new Outer(); out.outerFn(); } }
162
The Construction and enclosing this reference of Inner Classes Example: public class Outer{ int i=10; public class Inner{ int j; public void innerFn(){ System.out.println("i is "+ i); System.out.println("j is "+ j); } } public void innerCreate(){
Gaurav Gotra@ CDAC Noida 163
Inner in=new Inner(); in.innerFn(); } public void outerFn(){ System.out.println("i is "+ i); } public static void main(String s[]){ Outer out =new Outer(); out.innerCreate(); }
} You do at console:
javac Outer.java
java Outer i is 10 j is 0
Gaurav Gotra@ CDAC Noida 164
public class Outer{ int i=10; public class Inner{ int j; public void innerFn(){ System.out.println("i is "+ i); System.out.println("j is "+ j); } } public void outerFn(){ System.out.println("i is "+ i); } public static void main(String s[]){ Outer out =new Outer(); Outer.Inner in= out.new Inner(); in.innerFn(); } }
Gaurav Gotra@ CDAC Noida 165