0% found this document useful (0 votes)
244 views168 pages

Introduction To Java

The document discusses the basics of Java including its history and evolution from C and C++. It covers Java features like portability, security, object oriented concepts like encapsulation, inheritance and polymorphism. It also introduces basic Java programming concepts like data types, variables, operators, methods and classes.

Uploaded by

Shwetank Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
244 views168 pages

Introduction To Java

The document discusses the basics of Java including its history and evolution from C and C++. It covers Java features like portability, security, object oriented concepts like encapsulation, inheritance and polymorphism. It also introduces basic Java programming concepts like data types, variables, operators, methods and classes.

Uploaded by

Shwetank Sharma
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 168

Introduction To Java

Gaurav Gotra@ CDAC Noida

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

Importance and Features of Java


(13-Aug-2012)

Gaurav Gotra@ CDAC Noida

The Genesis of Java


Chronicle of Computer Languages B led to C, C evolved into C++ and C++ set the stage for Java. Computer Language innovation and development occurs for two fundamental reasons
To adapt to changing environments and uses. To implement refinements and improvements in the art of programming.

Gaurav Gotra@ CDAC Noida

Javas Lineage
From C, Java derives its syntax.
Many of Javas Object-Oriented features influenced by C++.

Gaurav Gotra@ CDAC Noida

The Birth of Modern Programming : C


Creation of C was a direct result of need for a structured,
efficient, high-level language that could replace assembly code when creating system programs. Fortran Good for Scientific Applications but not good for System Code. BASIC Easy to learn but not powerful for large programs. COBOL & Fortran relied upon GOTO produce spaghetti code a mass of tangled jumps and conditional branches that make a
program virtually impossible to understand

PASCAL Structured but not designed for Efficiency.


C Powerful, Efficient, Structured, Easy to learn language
Gaurav Gotra@ CDAC Noida 6

The Need for C++


Complexity
Structured Programming v/s Object Oriented Programming

Gaurav Gotra@ CDAC Noida

Structured Vs OOP
Structured Focuses on Process Follows Top Down Approach OOP Focuses on Object Follows Bottom Up Approach

Gaurav Gotra@ CDAC Noida

The Creation of Java


Portable, Platform Independent Language
World Wide Web, Internet

Gaurav Gotra@ CDAC Noida

Why Java is Important to the Internet


Java Application is a program that runs on your computer, under the
operating system of that computer.

Java Applet is an application designed to be transmitted over the


Internet and executed by a Java Compatible Browser. Security achieves this protection by confining a Java program to the Java Execution Environment and not allowing it access to other parts of computer. Portability Platform Independent Code. Javas Magic : The Byte Code Highly optimized set of instructions designed to be executed by the Java Virtual Machine (JVM) an interpreter for Byte Code.

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

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

The Three OOP Principles


Encapsulation mechanism that binds together code and the data it
manipulates and keeps both safe from outside interference and misuse.
Inheritance process by which one object acquires the properties of another object. Polymorphism feature that allows one interface to be used for a general class of actions.

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

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 ( )

Circle Object Draw (circle )

Box Object Draw (box )

Triangle Object Draw (triangle )

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.

Gaurav Gotra@ CDAC Noida

19

Example:

Suppose drawGraph() is a mechanism to draw a graph depending on the information provided,


DrawGraph(): Draws a point at any random location. DrawGraph(point1, point2) Draws a line from point1 to point2 DrawGraph(point1,point2,p Draw a rectangle using these points. oint3,point4)

Gaurav Gotra@ CDAC Noida

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.

Gaurav Gotra@ CDAC Noida

21

The figure below illustrates the process by which Java source code files are compiled and interpreted.
Source Code (Java files)

Java Compiler (javac.exe)

Bytecode (.Class file)

Standalone Application

Applet in Web Browser or Java VM

Java.exe

Executes Interpreted Applet


Executes Applet with JIT compiler

Gaurav Gotra@ CDAC Noida

22

A First Simple Program


/*

This is a simple Java Program Call this file Example.java


*/ Class Example { //your program begins with a call to main (). public static void main (String args[]) { System.out.println(This is a Simple Java Program); } }
Gaurav Gotra@ CDAC Noida 23

Compiling the Program


Compiling c:\>javac Example.java Running c:\>java Example Output This is a Simple Java Program

Gaurav Gotra@ CDAC Noida

24

Constants, Variables, Data Types, Operators, Expressions


(14-Aug-2012)

Gaurav Gotra@ CDAC Noida

25

Constants: Constants are declared using the final keyword. The


values of the constant can't be changed once its declared.

Example
public class varconstltr { public static final int constint=5; }

Gaurav Gotra@ CDAC Noida

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:

Primitive types Reference types

Data Types in Java

Java's Primitive Data Types


Gaurav Gotra@ CDAC Noida 27

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

-2 to 2 -1 15 15 -2 to 2 -1 31 31 -2 to 2 -1 -263 to 263-1 31 31 -2 to 2 -1 -263 to 263-1 0 to 215-1


true or false

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

This_is_an_insanely_long_variable_name_that_just _keeps_going_and_going_and_going_and_well_you_ge t_the_idea_The_line_breaks_arent_really_part_of_ the_variable_name_Its_just_that_this_variable_na me_is_so_ridiculously_long_that_it_won't_fit_on_ the_page_I_cant_imagine_why_you_would_need_such_ a_long_variable_name_but_if_you_do_you_can_have_ it


Gaurav Gotra@ CDAC Noida 29

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.

Gaurav Gotra@ CDAC Noida

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.

Gaurav Gotra@ CDAC Noida

33

The limits on both machines are as shown in the following table.


Floating 1.40239846e-45f 03.40282347e+38f (Minimum) (Maximum)

Double

4.94065645841246544e-324d 01.7976931348623157e+308d

(Minimum) (Maximum)

In addition, there are three unique states that floating-point numbers can have:

Negative_Infinity Positive_Infinity NaN


Literals

-1/0 1/0 Not a Number

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, Character, Number, Boolean.

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 \\ \ \

Gaurav Gotra@ CDAC Noida

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:

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

39

Arithmetic * / + % subtraction multiplication division addition modulo

Bitwise | ^ & >> << ~ >>> bitwise OR bitwise XOR bitwise AND right shift left shift bitwise NOT unsigned bit shift right
Gaurav Gotra@ CDAC Noida 40

Increment and Decrement Operators

++ - && || == ?: !

increment by one decrement by one


Logical boolean AND boolean OR boolean equals conditional not

Gaurav Gotra@ CDAC Noida

41

Operator Precedence in Java


Operator [] () . ++,-+, ~ ! (type) *, /, % +,+ Operator type Array index Parameter list Method invocation Arithmetic Arithmetic Integral Boolean Any Arithmetic Arithmetic String Description Used to access elements of an array Denotes a list of parameters Used to specify a method with in an object (or its hierarchy) Pre- or Post- increment/decrement Unary plus, unary minus Bitwise complement (unary) Logical Complement (Unary) Cast Multiplication, Division, reminder Addition, Substration String Concatenation

<< >>

Integral Integral

Left Shift Right shift with sign extension

Gaurav Gotra@ CDAC Noida

42

>>> <, <= >, >= Instanceof == != == != & ^ | && ||

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

Gaurav Gotra@ CDAC Noida

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:

Gaurav Gotra@ CDAC Noida

44

The Java Keywords


abstract assert boolean break byte case catch continue default do double else extends final goto if implements import instanceof int interface package private protected public return short static synchronized this throw throws transient try void

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. ( ), { }, . ;

Gaurav Gotra@ CDAC Noida

46

{ } defines blocks of code and automatically initializes arrays

[ ] declares array types and references array values


; terminates statements . separates successive identifiers in variable declarations.; chains statements in the test, expression of a for loop . Selects a field or method from an object; separates package names from sub-package and class names Parentheses in Java

// Print a Fahrenheit to Celsius table


class FahrToCelsius{ public static void main (String args[]) {
Gaurav Gotra@ CDAC Noida 47

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

Gaurav Gotra@ CDAC Noida

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

System.out.println("i k = i - x; System.out.println("i k = x - i; System.out.println("x k = i / x; System.out.println("i k = x / i; System.out.println("x


} }

x is " + k);
- x is " + k);

- i is " + k);
/ x is " + k); / i is " + k);

Gaurav Gotra@ CDAC Noida

52

i x i i i x i x

is 10 is 2.5 + x is 12.5 x is 25.0 - x is 7.5 - i is -7.5 / x is 4.0 / i is 0.25

Gaurav Gotra@ CDAC Noida

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:

double x = Double.valueOf("22.5").doubleValue(); float y = Float.valueOf("22.5").floatValue();


Gaurav Gotra@ CDAC Noida 54

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.

class Mc2 { public static void main (String args[]) {


double mass; double c = 2.998E8;// meters/second double E;
Gaurav Gotra@ CDAC Noida 55

mass = Double.valueOf(args[0]).doubleValue(); E = mass*c*c; System.out.println(E + " Joules"); } }

Here's the output: % javac Mc2.java % java Mc2 0.0456 4.09853e+15 Joules %

Gaurav Gotra@ CDAC Noida

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

You can use Unicode escape sequences instead like this


String Mj\u00F8lner = "Hammer of Thor";
Gaurav Gotra@ CDAC Noida 57

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)

Gaurav Gotra@ CDAC Noida

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:

int MyIntArray[]; int[] MyIntArray;


Create space for the array and define the size. To do this, you must use the keyword new, followed by the variable type and size:

MyIntArray = new int[500];


Gaurav Gotra@ CDAC Noida 60

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

Gaurav Gotra@ CDAC Noida

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)

Gaurav Gotra@ CDAC Noida

62

Here are some examples:


int[] k; float[] yt; String[] names; You also have the option to append the brackets to the variable name instead of the type. int k[]; float yt[]; String names[]; The choice is primarily one of personal preference. You can even use both at the same time like this: int[] k[]; float[] yt[]; String[] names[];
Gaurav Gotra@ CDAC Noida 63

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};

Gaurav Gotra@ CDAC Noida

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)

Gaurav Gotra@ CDAC Noida

68

Programming Constructs in Java Java Conditional Statements

The Java conditional statements can be built using the following:


if else else if while for do while switch case break continue goto return
Gaurav Gotra@ CDAC Noida 69

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.

Gaurav Gotra@ CDAC Noida

71

Testing for Equality

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

The while loop in Java

// 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

Gaurav Gotra@ CDAC Noida

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

This is the Hello program in Java using the do while loop:


class Hello { public static void main (String args[]) { int i = -1;
Gaurav Gotra@ CDAC Noida 75

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 } }

Gaurav Gotra@ CDAC Noida

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

The result is:

The strings are not the same.


Break

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;

Gaurav Gotra@ CDAC Noida

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

Here's the output:


% javac CountWheat.java % java CountWheat 26 1430 62 126 254 510 1022 204640948190 1638232766 65534 131070 262142 5242861048574 2097150 41943028388606 1677721433554430 67108862 134217726 268435454 536870910 1073741822 2147483646Error: Overflow All done! %

Gaurav Gotra@ CDAC Noida

80

The most common use of break is in switch statements.

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

Branching or Transfer statements (Contd..)


Return statements: It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. The returned value type must match the return type of method.
Syntax: return; return values; return; //This returns nothing. So this can be used when method is declared with void return type. return expression; //It returns the value evaluated from the expression.
Gaurav Gotra@ CDAC Noida 82

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); } }

Gaurav Gotra@ CDAC Noida

83

This code fragment prints


1, 2, 3, 4, 5, 6, 7, 8, 9, 1 1 1 1 1 1 1 1 1

Gaurav Gotra@ CDAC Noida

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); } }

This code fragment prints


1, 1 and then stops because j becomes equal to two and the outermost loop is exited.
Gaurav Gotra@ CDAC Noida 85

The switch statement in Java

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;

Gaurav Gotra@ CDAC Noida

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

Conditional (Logical) Operators (Contd..)


ternary ("?:") operator (contd..): It is basically is used for an if-then-else as shorthand as
boolean expression ? operand1 : operand2;

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

Gaurav Gotra@ CDAC Noida

88

The ?: operator in Java

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;

Gaurav Gotra@ CDAC Noida

89

Introducing Classes, Objects and Methods, Defining a Class, Adding Variables and Methods, Creating Objects
(23-Aug-2012)

Gaurav Gotra@ CDAC Noida

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

The General Form of a Class


class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodname2(parameter-list) { // body of method } // ... type methodnameN(parameter-list) { // body of method } } Gaurav Gotra@ CDAC Noida

92

A Simple Class
class Box { double width; double height; double depth; }

Gaurav Gotra@ CDAC Noida

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

The Term "Object"

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

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

96

Gaurav Gotra@ CDAC Noida

97

A Closer Look at new


the new operator dynamically allocates memory for an object. It has this general form: class-var = new classname( ); Here, class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. Constructors are an important part of all classes and have many significant attributes. Most real-world classes explicitly define their own constructors within their class definition. However, if no explicit constructor is specified, then Java will automatically supply a default constructor. It is important to understand that new allocates memory for an object during run time. The advantage of this approach is that your program can create as many or as few objects as it needs during the execution of your program. However, since memory is finite, it is possible that new will not be able to allocate memory for an object because insufficient memory exists. If this happens, a run-time exception will occur.
Gaurav Gotra@ CDAC Noida 98

Assigning Object Reference Variables


Box b1 = new Box(); Box b2 = b1;

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 }

Gaurav Gotra@ CDAC Noida

100

Adding a Method to the Box Class


class Box { double width; double height; double depth; // display volume of a box void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } }

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

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; } }

Gaurav Gotra@ CDAC Noida

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

Adding a Method That Takes Parameters


int square(int i) { return i * i; }

int x, y; x = square(5); // x equals 25 x = square(9); // x equals 81 y = 2; x = square(y); // x equals 4

Gaurav Gotra@ CDAC Noida

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; } }

Gaurav Gotra@ CDAC Noida

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); } }

Gaurav Gotra@ CDAC Noida

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

A Closer Look at Argument Passing


call-by-value This method copies the value of an argument
into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument.

call-by-reference - In this method, a reference to an


argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

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.

Gaurav Gotra@ CDAC Noida

116

// Returning an object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; } }

Gaurav Gotra@ CDAC Noida

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); } }

Gaurav Gotra@ CDAC Noida

118

Output ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

121

Constructors, Access Protection


(28-Aug-2012)

Gaurav Gotra@ CDAC Noida

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.

Gaurav Gotra@ CDAC Noida

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); } }

Gaurav Gotra@ CDAC Noida

125

Output Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0

Gaurav Gotra@ CDAC Noida

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.

Gaurav Gotra@ CDAC Noida

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); } }

Gaurav Gotra@ CDAC Noida

129

Output Volume is 3000.0 Volume is 162.0

Gaurav Gotra@ CDAC Noida

130

The Default Constructor


Java provides a Constructor with no argument and empty body. This default constructor makes you able to create an object with new operator by using syntax new Box();

Gaurav Gotra@ CDAC Noida

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; }

Gaurav Gotra@ CDAC Noida

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

Gaurav Gotra@ CDAC Noida

135

Difference b/w Methods & Constructor


Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

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

Access Protection (Contd..)


Private Same Class Yes No Modifier Yes Protected Yes Public Yes

Same Package Sub Class


Same Package Non Sub Class Different Package Sub Class Different Package Non Sub Class

No
No No No

Yes
Yes No No

Yes
Yes Yes No

Yes
Yes Yes Yes

Gaurav Gotra@ CDAC Noida

138

Access Modifiers
private protected default public

private access modifier


The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them.

Gaurav Gotra@ CDAC Noida

139

Access Modifiers Contd..


protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected member's class.

default access modifier


Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface.
Gaurav Gotra@ CDAC Noida 140

Access Modifiers Contd..


public access modifier
Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.

Gaurav Gotra@ CDAC Noida

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()); } }

Gaurav Gotra@ CDAC Noida

143

Other Topics
(28-Aug-2012)

Gaurav Gotra@ CDAC Noida

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.

Gaurav Gotra@ CDAC Noida

145

The super Keyword

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

The instanceof operator

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

Output Static block initialized. x = 42 a=3 b = 12

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( )

Gaurav Gotra@ CDAC Noida

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

The final KeyWord


The final modifier applies to classes, methods, and variables. The meaning of final varies from context to context, but the essential idea is the same: Final features may not be changed. A final class can not be subclassed. For example the code below will not compile, because the java.lang.String class is final

Gaurav Gotra@ CDAC Noida

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

public void draw(){ //code}


} This will give error like final method can not be overridden.

Gaurav Gotra@ CDAC Noida

157

The this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current object. That is, this is always a reference to the object on which the method was invoked. You can use this anywhere a reference to an object of the current class type is permitted.

// A redundant use of this. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; }


Gaurav Gotra@ CDAC Noida 158

The finalize() Method

Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or 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.

Gaurav Gotra@ CDAC Noida

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;

Gaurav Gotra@ CDAC Noida

161

public void innerFn(){ 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(); out.outerFn(); } }

Gaurav Gotra@ CDAC Noida

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

At console you do: javac Outer.java java Outer i is 10 j is 0

Important points about Inner Classes:


Inner class can be static. Inner class can be abstract. A static inner class is just like a top level class. An inner class can not have any static variable declared inside it.
Gaurav Gotra@ CDAC Noida 166

Anonymous Inner Classes


An anonymous inner class is one that is not assigned a name. public class AnonymousInnerClassDemo extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } }); } } Gaurav Gotra@ CDAC Noida 167

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]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1
Gaurav Gotra@ CDAC Noida 168

You might also like