Chettinad College of Engineering & Technology/II-MCA/ MC9235 Web Programming WEB PROGRAMMING DEPARTMENT OF MCA

Similar documents
Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

These two items are all you'll need to write your first application reading instructions in English.

CS11 Java. Fall Lecture 1

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Full file at

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Pace University. Fundamental Concepts of CS121 1

4 Programming Fundamentals. Introduction to Programming 1 1

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Lecture 1: Overview of Java

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Java Bytecode (binary file)

1 Lexical Considerations

Basics of Java Programming

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Language Fundamentals Summary

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

A variable is a name that represents a value. For

13 th Windsor Regional Secondary School Computer Programming Competition

Index COPYRIGHTED MATERIAL

Lexical Considerations

Java Overview An introduction to the Java Programming Language

Introduction to Programming Using Java (98-388)

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Lexical Considerations

Programming. Syntax and Semantics

Introduction To Java. Chapter 1. Origins of the Java Language. Origins of the Java Language. Objects and Methods. Origins of the Java Language

Java Programming. Atul Prakash

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

3. Java - Language Constructs I

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Java+- Language Reference Manual

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Notes. 10th ICSE. Saravanan Ganesh

Object-Oriented Programming

Operators. Java operators are classified into three categories:

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Java Basic Datatypees

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Introduction to Java & Fundamental Data Types

2 rd class Department of Programming. OOP with Java Programming

Introduction to Java

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Chapter 3: Operators, Expressions and Type Conversion

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

UNIT- 3 Introduction to C++

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Java is an objet-oriented programming language providing features that support

Zheng-Liang Lu Java Programming 45 / 79

Course Outline. Introduction to java

JAVA Programming Fundamentals

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Computer Components. Software{ User Programs. Operating System. Hardware

Visual C# Instructor s Manual Table of Contents

Fundamentals of Programming. By Budditha Hettige

Work relative to other classes

Review of the C Programming Language for Principles of Operating Systems

Contents. Jairo Pava COMS W4115 June 28, 2013 LEARN: Language Reference Manual

Language Reference Manual simplicity

Course information. Petr Hnětynka 2/2 Zk/Z

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Simple Java Reference

CS 231 Data Structures and Algorithms, Fall 2016

Programming with Java

Accelerating Information Technology Innovation

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

Preview from Notesale.co.uk Page 9 of 108

CSC 1214: Object-Oriented Programming

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Java Identifiers. Java Language Essentials. Java Keywords. Java Applications have Class. Slide Set 2: Java Essentials. Copyright 2012 R.M.

Chapter 2: Basic Elements of C++

History of Java. Java was originally developed by Sun Microsystems star:ng in This language was ini:ally called Oak Renamed Java in 1995

CS260 Intro to Java & Android 03.Java Language Basics

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Getting started with Java

Sri Vidya College of Engineering & Technology

JME Language Reference Manual

Room 3P16 Telephone: extension ~irjohnson/uqc146s1.html

Certified Core Java Developer VS-1036

Java: framework overview and in-the-small features

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

C OVERVIEW BASIC C PROGRAM STRUCTURE. C Overview. Basic C Program Structure

1 Shyam sir JAVA Notes

Outline. Why Java? (1/2) Why Java? (2/2) Java Compiler and Virtual Machine. Classes. COMP9024: Data Structures and Algorithms

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

JAVA OPERATORS GENERAL

The Java language has a wide variety of modifiers, including the following:

Unit-II Programming and Problem Solving (BE1/4 CSE-2)

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Transcription:

WEB PROGRAMMING DEPARTMENT OF MCA Class II MCA Semester III Batch & Year B4 & 2012 Staff A.SALEEM RAJA, MCA.,M.Phil.,M.Tech Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 1

UNIT III JAVA FUNDAMENTALS Java features Java Platform Java Fundamentals Expressions, Operators, and Control Structures Classes, Packages and Interfaces Exception Handling. Objective Chapter 1 The Java Programming Language Learn the characteristics of Java Understand Java platform. Understand how a Java program is written, compiled, and executed. Origin of Java Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called Oak but was renamed Java in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995, many more people contributed to the design and evolution of the language. Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the original prototype. Java technology is both a programming language and a platform. The Java programming language is a high-level language that can be characterized by all of the following buzzwords: Simple Architecture neutral Object oriented Portable Distributed Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 2

High performance Multithreaded Robust Dynamic Secure The Java Platform A platform is the hardware or software environment in which a program runs. Some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 3

be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components: Java Virtual Machine Java Application Programming Interface (API) Java Virtual Machine In the Java programming language, all source code is first written in plain text files ending with the.java extension. Those source files are then compiled into.class files by the javac compiler. A.class file does not contain code that is native to our processor; it instead contains bytecodes the machine language of the Java Virtual Machine (Java VM). The java launcher tool then runs our application with an instance of the Java Virtual Machine. Because the Java VM is available on many different operating systems, the same.class files are capable of running on Microsoft Windows, the Solaris TM Operating System (Solaris OS), Linux, or Mac OS. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 4

Through the Java VM, the same application is capable of running on multiple platforms. Java Application Programming Interface (API) The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The API and Java Virtual Machine insulate the program from the underlying hardware. As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability. First Step into Java Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 5

It's time to write our first application! The following instructions are for users of Windows XP Professional, Windows XP Home, Windows Server 2003, Windows 2000 Professional, and Windows Vista. To write our first program, we'll need: 1. The Java SE Development Kit 6 (JDK 6) We can download the Windows version : http://java.sun.com /javase/downloads/index_jdk5.jsp. (Make sure you download the JDK, not the JRE.). Install the JDK 6 properly. 2. A text editor In this example, we'll use Notepad, a simple editor included with the Windows platforms. These two items are all we'll need to write your first application. Creating Our First Application Our first application, HelloWorldApp, will simply display the greeting "Hello world!". To create this program, we will: Create a source file A source file contains code, written in the Java programming language. Use any text editor to create and edit source files. Compile the source file into a.class file The Java programming language compiler (javac) takes our source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes. Run the program Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 6

The Java application launcher tool (java) uses the Java virtual machine to run our application. Create a Source File First, start our editor. Launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); // Display the string. Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save As menu item. Then, in the Save As dialog box: 1. Using the Save in combo box, specify the folder (directory) where we'll save our file. In this example, the directory is java on the C drive. 2. In the File name text field, type "HelloWorldApp.java", including the quotation marks. 3. From the Save as type combo box, choose Text Documents (*.txt). 4. In the Encoding combo box, leave the encoding as ANSI. When we're finished, the dialog box should look like this. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 7

Now click Save, and exit Notepad. Compile the Source File into a.class File The Save As dialog just before click Save. Bring up a shell, or "command," window. We can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run... and then entering cmd. The shell window should look similar to the following figure. A shell window. The prompt shows our current directory. When we bring up the prompt, our current directory is usually our home directory for Windows XP (as shown in the preceding figure). Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 8

To compile our source file, change our current directory to the directory where our file is located. For example, if our source directory is java on the C drive, type the following command at the prompt and press Enter: cd C:\java Now the prompt should change to C:\java>. If we enter dir at the prompt, we can see our source file, as the following figure shows. Directory listing showing the.java source file. Now we are ready to compile. At the prompt, type the following command and press Enter. javac HelloWorldApp.java The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file that was generated, as shown in the following figure. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 9

Directory listing, showing the generated.class file Now that we have a.class file, we can run your program. Run the Program In the same directory, enter the following command at the prompt: java HelloWorldApp The next figure shows what you should now see: The program prints "Hello World!" to the screen. A Closer Look at the "Hello World!" Application The "Hello World!" application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. Source Code Comments The following bold text defines the comments of the "Hello World!" application: /** * The HelloWorldApp class implements an application that * simply prints "Hello World!" to standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); // Display the string. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 10

Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments: /* text */ The compiler ignores everything from /* to */. /** documentation */ This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The javadoc tool uses doc comments when preparing automatically generated documentation. // text The compiler ignores everything from // to the end of the line. The HelloWorldApp Class Definition The following bold text begins the class definition block for the "Hello World!" application: /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); // Display the string. As shown above, the most basic form of a class definition is: class name {... Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 11

The keyword class begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces marked in bold above. The main Method The following bold text begins the definition of the main method: /** * The HelloWorldApp class implements an application that * simply displays "Hello World!" to the standard output. */ class HelloWorldApp { public static void main(string[] args) { System.out.println("Hello World!"); //Display the string. In the Java programming language, every application must contain a main method whose signature is: public static void main(string[] args) The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. We can name the argument anything we want, but most programmers choose "args" or "argv". The main method accepts a single argument: an array of elements of type String. public static void main(string[] args) This array is the mechanism through which the runtime system passes information to our application. For example: java MyApp arg1 arg2 Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 12

The "Hello World!" application ignores its command-line arguments, but we should be aware of the fact that such arguments do exist. Finally, the line: System.out.println("Hello World!"); uses the System class from the core library to print the "Hello World!" message to standard output. Objectives Learn the Java s most fundamental elements: Data types Variables Keywords Arrays Data type enum Operators Control Statements Block Breaker Statements Data Types and Variables Chapter 2 Language Basics A computer program, written in any programming language, is basically made of three elements: data, operations on data, and the logic that determines the operations. Therefore, manipulating the data (i.e. holding and operating on it) is at the core of a typical computer program. The data is held by variables, and the operations are made by using what are called operators. Data handled by the program may come in different types, such as integer or character. Every language supports certain basic data types, called primitive data types. However, a given variable may hold data of one specific type only. Data Types Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 13

Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float, double, and boolean. These can be put in four groups: Integers This group includes byte, short, int, and long, which are for wholevalued signed numbers. Floating-point numbers This group includes float and double, which represent numbers with fractional precision. Characters This group includes char, which represents symbols in a character set, like letters and numbers. Boolean This group includes boolean, which is a special type for representing true/false values. byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of - 2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). float: The float data type is a single-precision 32-bit of storage. It has an approximate range from 1.4e-045 to 3.4e+038 double: The double data type is a double-precision 64-bit of storage. It has an approximate range from 4.9e 324 to 1.8e+308 boolean: The boolean data type has only two possible values: true and false. char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive). Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 14

In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.string class. Enclosing our character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language. The following chart summarizes the default values for the above data types. Data Type Default Value (for fields) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d char '\u0000' String (or any object) null boolean false Table: Primitive Data Types, Their Sizes, and the Ranges of Their Values Literals A literal is the source code representation of a fixed value; literals are represented directly in our code without requiring computation. Integer Literals Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 15

Integers are probably the most commonly used type in the typical program. Any whole number value is an integer literal. Examples are 1, 2, 3, and 42. As shown below, it's possible to assign a literal to a variable of a primitive type: boolean result = true; char capitalc = 'C'; byte b = 100; short s = 10000; int i = 100000; Floating-Point Literals Floating-point numbers represent decimal values with a fractional component. They can be expressed in either standard or scientific notation. Standard notation consists of a whole number component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers. Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E 05, and 2e+100. As shown below, it's possible to assign a literal to a variable of a primitive type: double d1 = 123.4; double d2 = 1.234e2; // same value as d1, but in scientific notation float f1 = 123.4f; Boolean Literals Boolean literals are simple. There are only two logical values that a boolean value can have, true and false. The values of true and false do not convert into any numerical representation. The true literal in Java does not equal 1, nor does the false literal equal 0. In Java, they can only be assigned to variables declared as boolean, or used in expressions with Boolean operators. Character Literals Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into integers and manipulated with the integer operators, such as the addition and Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 16

subtraction operators. A literal character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered inside the quotes, such as a, z, and @. String Literals String literals in Java are specified like they are in most other languages by enclosing a sequence of characters between a pair of double quotes. Examples of string literals are Hello World two\nlines \ This is in quotes\ Character Escape Sequences Escape Sequence Description \ddd Octal character (ddd) \uxxxx Hexadecimal UNICODE character (xxxx) \ Single quote \ Double quote \\ Backslash \r Carriage return \n New line (also known as line feed) \f Form feed \t Tab \b Backspace Variables The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope, which defines their visibility, and a lifetime. Declaring the variable In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown here: type identifier [ = value][, identifier [= value]...] ; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 17

The type is one of Java s atomic types, or the name of a class or interface. The identifier is the name of the variable. We can initialize the variable by specifying an equal sign and a value. Keep in mind that the initialization expression must result in a value of the same (or compatible) type as that specified for the variable. To declare more than one variable of the specified type, use a comma-separated list. Here are several examples of variable declarations of various types. Note that some include an initialization. int a, b, c; // declares three ints, a, b, and c. int d = 3, e, f = 5; // declares three more ints, initializing d and f. byte z = 22; // initializes z. double pi = 3.14159; // declares an approximation of pi. char x = 'x'; // the variable x has the value 'x'. Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. Naming the Variables: Legal Identifiers Each variable has a name, given to it by the programmer while declaring the variable. This name is called an identifier. For example, v1 is an example of an identifier. Following are the rules to name a variable (or define an identifier): The first character of an identifier must be a letter, a dollar sign ($), or an underscore (_). A character other than the first character in an identifier may be a letter, a dollar sign, an underscore, or a digit. None of the Java language keywords (or reserved words) can be used as identifiers. Scope and Lifetime of Variables Java allows variables to be declared within any block. A block is begun with an opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time we start a new block, we are creating a new scope. A scope determines what objects are visible to other parts of our program. It also determines the lifetime of those objects. A variable can be accessed only within its scope, which is the area in the program from which it can be legally referred to. From the viewpoint of scope, variables can be classified into three categories: Local variables: All the variables declared inside a method. Their scope is the method. In other words, they can be accessed only from inside the method in which they are Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 18

declared, and they are destroyed when the method completes. Local variables are also called stack variables because they live on the stack. Instance variables: The variables declared inside a class but outside of any method. Their scope is the instance of the class in which they are declared. These variables, for example, can be used to maintain a counter at instance level. Instance variables live on the heap. Static variables: The instance variables declared with the modifier static. Their scope is the class in which they are declared. These variables can be used to maintain a counter at class level, which is a variable shared by all the objects of the class. Reserved Names: The Keywords Java keywords are the reserved words in the Java language. Each keyword has a specific meaning within the language. Therefore, a programmer cannot use these words to name the variables, classes, or methods. For example, the word int is a keyword used to declare a variable of type integer. The Java keywords are listed in Table Below. Table: Keywords in Java Keywords use letters only; they do not use special characters (such as $, _, etc.) or digits. All keywords are in all lowercase letters. Arrays Arrays in Java are objects that are used to store multiple variables of the same type. These variables may be of primitive types or of non-primitive types (i.e. object references). Whether an array stores a primitive variable or an object reference, the array itself is always an object. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 19

We declare an array by specifying the data type of the elements that the array will hold, followed by the identifier, plus a pair of square brackets before or after the identifier. The data type may be a primitive or a class. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a convenient means of grouping related information. Making an array of data items consists of three logical steps: 1. Declare an array variable. 2. Create an array of a certain size and assign it to the array variable. 3. Assign a value to each array element. An array of ten elements Declaring an Array Variable Following is an example of declaring an array variable of primitive data type int: int[] scores; The following is also legal: int scores []; Similarly, the following is an example of declaring an array variable of a non-primitive data type, where Student is the name of a class: Student[] students; Again, the following is also a legal declaration: Student students[]; It is not legal to include the size of an array in the declaration. For example, the compiler will generate an error on the following statement: int [5] scores; The size is included when we create the array. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 20

Creating an Array Because an array is an object, we create it with the new operator. An array of primitives is created and assigned to an already declared array variable as shown in this example: scores = new int[3]; This statement creates an array of three elements that can hold integer values and assigns it to the array variable scores, which is already declared. An array of a non-primitive data type is created and assigned to an already declared array variable as shown in the following example: students = new Student[3]; This statement creates an array of three elements that can hold object references (which will reference to the objects of the Student class) and assigns it to the array variable students, which we have already declared. Assigning Values to Array Elements Each element of an array needs to be assigned a value, which may be data of a primitive type or a reference to an object, depending upon the type of the array. The value is assigned by referring to the array element, as shown in the following code fragment: scores[0] = 75; scores[1] = 80; scores[2] = 100; So, elements of an int array just act like int variables. Similarly, elements in an object array act like object reference variables: students[0] = new Student(); students[1] = new Student(); students[2] = new Student(); This code will create three Student objects on the heap and assign each of them to the corresponding array element. Note that the index value for an array starts from 0; that is, if an array is of size 5, the index for the first element is 0 and the index for the last element is 4. Also, once we have created an array of a specific size, we cannot change the size. Multidimensional Arrays Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 21

In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called twod. int twod[][] = new int[4][5]; This allocates a 4 by 5 array and assigns it to twod. Internally this matrix is implemented as an array of arrays of int. Conceptually, this array will look like the one shown in Figure. Program: One Dimensional Array //Program that creates an array of the number of days in each month. // Demonstrate a one-dimensional array. class Array { public static void main(string args[]) { int month_days[]; month_days = new int[12]; month_days[0] = 31; month_days[1] = 28; month_days[2] = 31; month_days[3] = 30; month_days[4] = 31; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 22

month_days[5] = 30; month_days[6] = 31; month_days[7] = 31; month_days[8] = 30; month_days[9] = 31; month_days[10] = 30; month_days[11] = 31; System.out.println("April has " + month_days[3] + " days."); When we run this program, it prints the number of days in April. Note: Java strictly checks to make sure we do not accidentally try to store or reference values outside of the range of the array. The Java run-time system will check to be sure that all array indexes are in the correct range. (In this regard, Java is fundamentally different from C/C++, which provides no run-time boundary checks.) Program: Two Dimensional Arrays // Demonstrate a two-dimensional array. class TwoDArray { public static void main(string args[]) { int twod[][]= new int[4][5]; int i, j, k = 0; for(i=0; i<4; i++) for(j=0; j<5; j++) { twod[i][j] = k; k++; for(i=0; i<4; i++) { for(j=0; j<5; j++) System.out.print(twoD[i][j] + " "); System.out.println(); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 23

This program generates the following output: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Data Type enum The data type enum, introduced in J2SE 5.0, is useful when we want a variable to hold only a predetermined set of values. We should use enum any time as we need a fixed set of constants, including natural enumerated types such as days of the week. We can define an enum variable in two steps: 1. Define the enum type with a set of named values. 2. Define a variable to hold one of those values. Following is an example: enum AllowedCreditCard {VISA, MASTER_CARD, AMERICAN_EXPRESS; AllowedCreditCard visa = AllowedCreditCard.VISA; A value stored in an instance of an enum is retrieved by referring to it just like a variable, as shown in this example: System.out.println("The allowed credit card value: " + visa) Operators in Java Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. Java provides a rich operator environment. First, let s look at the operators in a rather generic way. From the perspective of the number of operands they operate on, Java operators can be classified into the following three categories: Unary operators: Require only one operand. For example: ++ increments the value of its operand by one. Binary operators: Require two operands. For example: + adds the values of its two operands. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 24

Ternary operators: Operate on three operands. The Java programming language has one ternary operator (?:). Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations. Arithmetic Operators In mathematics, we are all familiar with the arithmetic operators, which perform arithmetic operations on their operands, and apply to operands of any numeric type. The arithmetic operators supported by the Java programming language are summarized in Table Table 2.7.1: Arithmetic Operators The Unary Arithmetic Operators The unary operators are of two kinds: those that just change the sign, called the sign unary operators, and those that change the absolute value of the operand, called increment and decrement operators. The Sign Unary Operators: + and These operators do not change the absolute value of the operand, only the sign. The + operator does not have any real effect. The operator multiplies the value of the operand by -1 before assigning it to another operand. However, it does not change the absolute value of the operand on which it operates. The Increment and Decrement Operators: ++ and -- The operators ++ and -- increment and decrement the value of an operand by 1. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 25

Table 2.7.2: Increment and Decrement Operators: ++ and -- Bitwise Logical Operators Java offers some logical operators that are used to manipulate (test, or set) the bits of an integer (byte, short, char, int, long) value. These operators act upon the individual bits of their operands. They are summarized in the following table: Table 2.7.3: Bitwise Logical Operators The bitwise logical operators are &,, ^, and ~. The following table shows the outcome of each operation. Relational Operators A relational operator, also called a comparison operator, compares the values of two operands and returns a Boolean value: true or false. In other words, a comparison operator tests a relationship between two operands to be true or false. For this reason, comparison operators are also called relational operators. The operand could be any of the numeric operands. Table below summarizes the comparison operators. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 26

Table 2.7.4: Relational Operators Logical Operators Logical operators are used to combine more than one condition that may be true or false. In other words, logical operators deal with connecting the boolean values. These operators are called short-circuit logical operators. The outcome of these operators is, of course, a boolean. These operators are summarized in Table. Table 2.7.5: Logical Operators Assignment Operators An assignment operator is used to set (or reset) the value of a variable. The most common and obvious assignment operator is =. For example, the following code statement declares a variable x of type int and sets its value to 7: int x = 7; There are several shortcut assignment operators that reduce down to the basic assignment operator. These shortcut assignment operators are summarized in Table. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 27

Table 2.7.6: Shortcut Assignment Operators Advanced Operators In addition to the operators discussed so far in this chapter, Java offers a few more operators, summarized in Table: Operator Precedence Table 2.7.7: Advanced Operators Operator Precedence Operators Precedence postfix expr++ expr-- unary ++expr --expr +expr -expr ~! multiplicative * / % additive + - shift << >> >>> Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 28

relational < > <= >= instanceof equality ==!= bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR logical AND && logical OR ternary? : assignment = += -= *= /= %= &= ^= = <<= >>= >>>= Control statements in Java The order in which the code statements will be executed is an important component of the internal architecture of a program. In a given block, the program is executed sequentially one statement at a time starting from the first statement at the top and proceeding toward the bottom. This scheme, without any additional flow logic, will execute each statement precisely once. However, if a programming language is to allow us to write programs to solve real-life problems, it must recognize the conditional logic that is at work in real life. A set of statements may be executed once, more than once, or skipped altogether, and the decision may be made at runtime (that is, at the time of program execution). This makes programming more dynamic, efficient, and powerful. Java s program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow our program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion. Selection statements The selection statements, also called the decision statements, are of two types: if and switch. if Statements Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 29

The if statements can handle a range of conditions starting from very simple to quite sophisticated. Accordingly, they come in four different constructs: if, if-else, if-else if, and if-else if-else. The if Construct The if construct allows the execution of a single statement or a block of statements enclosed within curly braces. The syntax of the if construct is shown here: if( <expression> ) { // if <expression> returns true, the statements in this // blocks are executed. If there is only one statement in the block, the curly braces are not mandatory, but it is a good programming practice to use the curly braces regardless of whether there is one or more statements to execute. Following is an example of an if statement: if ( x > 0 ) { System.out.println("x is greater than zero."); The if-else Construct We can handle two blocks of code with the if-else construct. If a condition is true, the first block of code will be executed, otherwise the second block of code will be executed. The syntax for the if-else construct follows: if( <expression> ) { // if <expression> returns true, statements in this block are executed. else { // if <expression> is false, then statements in this block will be executed. For example, consider the following code fragment: if ( x > 0 ) { System.out.println("x is greater than zero."); else { Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 30

System.out.println("x is not greater than zero."); The if-else if Construct With the if-else if construct we can handle multiple blocks of code, and only one of those blocks will be executed at most. The syntax for the if-else construct follows: if( <expression1> ) { // if <expression1> returns true, statements in this block are executed. else if ( <expression2>) { // if <expression1> is false and <expression2> is true, then statements in this block will be executed. else if (<expression3>) { // if <expression1> is false, and <expression2> is false, and <expression3> is true, then statements in this block will be executed. The if-else if-else Construct The syntax for the if-else if-else construct follows: if( <expression1> ) { // if <expression1> returns true, statements in this block are executed. else if (<expression2>) { // if <expression1> is false and <expression2> is true, then statements in this block will be executed. else if (<expression3>) { // if <expression1> is false and <expression2> is false, and <expression3> is true, then statements in this block will be executed. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 31

else { // if the expression in the if statement and the expressions in all the else if statements were false, then the statements in this block will be executed. Program: if-else-if statements // Demonstrate if-else-if statements. class IfElse { public static void main(string args[]) { int month = 4; // April String season; if(month == 12 month == 1 month == 2) season = "Winter"; else if(month == 3 month == 4 month == 5) season = "Spring"; else if(month == 6 month == 7 month == 8) season = "Summer"; else if(month == 9 month == 10 month == 11) season = "Autumn"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); Here is the output produced by the program: April is in the Spring. switch Statements The switch statement is Java s multi-way branch statement. It provides an easy way to dispatch execution to different parts of our code based on the value of an expression. As such, it often Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 32

provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement: switch (expression) { case value1: // statement sequence break; case value2: // statement sequence break;... case valuen: // statement sequence break; default: // default statement sequence The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed. Program: switch Statement // A simple example of the switch. class SampleSwitch { public static void main(string args[]) { for(int i=0; i<6; i++) switch(i) { case 0: System.out.println("i is zero."); break; case 1: System.out.println("i is one."); break; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 33

case 2: System.out.println("i is two."); break; case 3: System.out.println("i is three."); break; default: System.out.println("i is greater than 3."); The output produced by this program is shown here: i is zero. i is one. i is two. i is three. i is greater than 3. i is greater than 3. Iteration Statements There will be situations in programming in which we want to have a block of statements executed over and over again as long as a certain condition is true. This is accomplished by using the iteration statements. In order to facilitate iterative execution, Java offers four iteration constructs: while, do-while, for, and for-each. The while Loop Construct The while loop construct handles the situation in which a block is executed for the first time only when a condition is true. After execution the condition is checked again, and as long as the condition stays true, the block is executed repeatedly. The syntax for the while loop construct follows: while ( <expression> ) { // if the <expression> is true, execute the statements in this block. // After the execution, go back to check the condition again. Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 34

The <expression> in the parentheses of while is a boolean condition that returns true or false. For example, consider a while loop that counts down from 10, printing exactly ten lines of tick : Program: while Loop // Demonstrate the while loop. class While { public static void main(string args[]) { int n = 10; while(n > 0) { System.out.println("tick " + n); n--; When we run this program, it will tick ten times: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 The do-while Loop Construct The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. The syntax for the do-while construct follows: do { // Execute the statements in this block. while ( <expression> ); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 35

Again, the <expression> is a boolean condition that returns true or false. When the execution control arrives at do, it enters the do block. After executing the statements in the do block, the expression specified by <expression> is executed. If it returns true, the control goes back to the do statement and the do block is executed again. Note: The do-while loop will be executed at least once, whereas, depending upon the expression, the while loop may not be executed at all. For example, Here is a reworked version of the tick program that demonstrates the do-while loop. It generates the same output as before. Program: do-while Loop // Demonstrate the do-while loop. class DoWhile { public static void main(string args[]) { int n = 10; do { System.out.println("tick " + n); n--; while(n > 0); When we run this program, it will tick ten times: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 36

The for Loop Construct The for loop is the most sophisticated of all the loop constructs and provides a richer functionality as a result. The syntax for the for loop construct is shown here: for ( <statement>; <test>; <expression>) { // if the <test> is true, execute the block. The following list explains the arguments (the three elements appearing in the parentheses) of the for construct: <statement>: Often used to initialize the iteration variable that will monitor the iteration (e.g. i=0). The variable may also be declared and initialized (e.g. int i = 0). The <statement> is executed only once, when the control comes to the for loop for the first time. <test>: A boolean condition that returns either true or false. The for block is executed repeatedly until the <test> returns false. Depending upon the test, and the value of the iteration variable, the for block may never be executed. <expression>: Executed immediately after the execution of the for block, each time the for block is executed. Generally, it is used to change the value of the iteration variable, also called the loop counter. If the <test> returns true, the for block will be executed. Immediately after the block execution, <expression> will be executed. Then the <test> will be executed again. If it returns true, the block will be executed again. Following this, <expression> will be executed again, and so on. When <test> returns false, the execution control jumps to the first statement immediately after the for block. Program: do-while Loop // Demonstrate the for loop. class ForTick { public static void main(string args[]) { int n; for(n=10; n>0; n--) System.out.println("tick " + n); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 37

When we run this program, it will tick ten times: tick 10 tick 9 tick 8 tick 7 tick 6 tick 5 tick 4 tick 3 tick 2 tick 1 More About Arguments of the for() Construct: Beware! We must remember some rules for the elements in the parentheses of the for() construct. To start, the <statement> in for() has to be a code statement. For example, if i is already declared and initialized, the following code line will generate a compiler error: for (i; i<5; i++) However, the following code line will work: for (i=i+1; i<5; i++) The <statement> may have two non-declarative expressions, separated by a comma. For example, the following is a valid code line: for( i++, j++ ; i+j < 5 ; i++) However, the <statement> cannot have multiple declarations or a mix of a declarative and nondeclarative statement. For example, both of the following lines of code are illegal and will generate compiler errors: for ( int i = 0, int j = 0; i+j < 5; i++) for (int i = 0; i = i + 1; i + j < 5; i++ ) Any of the three components in the parentheses of for() may be omitted, but the semicolons cannot be. For example, the following is a legal code fragment that generates an infinite loop: for(; ;) { System.out.println ("Round and round we go for ever."); Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 38

However, the following code fragment will generate a compiler error: for() { System.out.println ("Round and round we go for ever."); Another thing to note is that a variable declared inside a for loop will not exist (and hence cannot be used) outside the for loop. If a variable is declared before the for loop, even though initialized in the for() statement, it will exist (and hence can be used) even after the for loop. Note: A variable declared inside a for loop cannot be accessed from outside the for loop, whereas a variable only initialized inside a for loop, and declared before it, can also be accessed after the for loop is executed. A programmer often iterates over the elements of a list, array, or any other collection. Previously, there was not an automated way to do it in Java, and hence such looping was prone to errors. J2SE 5.0 has introduced a solution to this problem in the form of the for-each loop construct. The for-each Loop Construct The for-each loop construct, introduced in J2SE 5.0, makes it easier and less error prone to iterate through the elements of an array and any other collection. The syntax for this construct is shown here: for (<variable> : <collection>) { // the block code It sets the <variable> to the first element of the collection during the first iteration, to the second element during the second iteration, and so on. Iterations are performed automatically for all the elements of the collection. Program: for-each Loop class ForEachTest { public static void main(string[] args) { int[] myarray = new int[3]; myarray[0]= 10; myarray[1] = 20; Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 39

myarray[2] = 30; for(int i : myarray) { System.out.println (i); The output of program follows: 10 20 30 Block Breaker Statements There will be situations in a program when you want to quit either the current iteration of a loop or the entire loop altogether. To handle such situations, Java offers two block breaker statements: continue and break. The continue Statement The continue statement, in its simplest form, has the following syntax: continue; When this statement is executed, the current iteration of the block execution is terminated, and the control jumps to the next iteration of the block according to the following rules: If the continue statement is in the while, or do-while, block, control jumps to the Boolean condition in the parentheses of while. If the continue statement is in the for block, control jumps to the <expression> in the for (<statement>; <test>; <expression>) statement. For example, consider the following code fragment: for ( int i = 0; i < 5; i++ ) { if ( i == 3 ) continue; System.println ( "The value of i is " + i ); This generates the following output: The value of i is 0 The value of i is 1 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 40

The value of i is 2 The value of i is 4 The line the value of i is 3 is missing from the output due to the continue statement. Note: The continue statement is only valid inside a loop. If we write it outside the loop, your program will generate a compiler error. The break Statement Whereas the continue statement breaks the execution control out of the current block iteration to the next iteration, the break statement throws the execution control out of the block altogether. However, note that a break statement may be used either in a loop or in a switch block. The break statement, in its simplest form, has the following syntax: break; For example, consider the following code fragment: for ( int i = 3; i >0; i-- ) { for (int j = 0; j<4; j++) { System.out.println ( "i=" + i + " and j=" + j); if ( i == j ) break; This will generate the following output: i=3 and j=0 i=3 and j=1 i=3 and j=2 i=3 and j=3 i=2 and j=0 i=2 and j=1 i=2 and j=2 i=1 and j=0 i=1 and j=1 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 41

Objective Chapter 3 Working with Classes and Objects At the end of this session, students can learn Basics of class and objects. Methods and Modifiers Constructors Usage of final, finalize () Nested and Inner Class Command line Arguments Classes The class is the basis for object-oriented programming. The data and the operations on the data are encapsulated in a class. In other words, a class is a template that contains the data variables and the methods that operate on those data variables following some logic. So, the class is the foundation on which the entire Java language is built. All the programming activity happens inside classes. The data variables and the methods in a class are called class members. Variables, which hold the data (or point to it in case of reference variables), are said to represent the state of an object (that may be created out of the class), and the methods constitute its behavior. Defining Classes A class is declared by using the keyword class. The general syntax for a class declaration is <modifier> class <classname> { <classname> specifies the name of the class, class is the keyword, and <modifier> specifies some characteristics of the class. The <modifier> specification is optional, but the other two elements in the declaration are mandatory. We can broadly group the modifiers into the following two categories: Access modifiers: Determine from where the class can be accessed: private, protected, and public. If you do not specify an access modifier, the default access is assumed. Other modifiers: Specify how the class can be used: abstract, final, and strictfp. As an example of an access modifier, consider the following class declaration: Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 42

class MyClass { Because no access modifier is declared in the preceding class declaration, the default access is assumed. As an example of a non-access modifier, we can declare an abstract class by specifying the abstract modifier, as in the following: abstract class MyClass { The class code that contains the class members (variables and methods) is written inside two curly braces. Program below presents an example of a full definition (declaration plus code) of a simple class. Program: Class class ClassRoom { private String roomnumber; private int totalseats = 60; private static int totalrooms = 0; void setroomnumber(string rn) { roomnumber = rn; String getroomnumber() { return roomnumber; void settotalseats(int seats) { totalseats = seats; int gettotalseats() { return totalseats; The class defined in above program has the following class members: The instance variables roomnumber and totalseats The class (static) variable totalrooms Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 43

The methods setroomnumber( ), getroomnumber(), settotalseats( ), and gettotalseats() In object-oriented programming, a problem is solved by creating objects in a program that correspond to the objects in the real problem, such as student and classroom. A class is a template or a blueprint for creating objects. Creating Objects When we write a class, we must keep in mind the objects that will be created from it, which correspond to the objects in the problem that is being solved by the program. We may also look upon the classes as data types. We can declare a variable (a reference variable) of a class and assign it a value with the following syntax: <classname> <variablename> = new <classconstructor> <variablename> in this case is the name of the object reference that will refer to the object that we want to create, and we choose this name. <classname> is the name of an existing class, and <classconstructor> is a constructor of the class. The right side of the equation creates the object of the class specified by <classname> with the new operator, and assigns it to <variablename> (i.e. <variablename> points to it). Creating an object from a class this way is also called instantiating the class. For example, consider the following code fragment: class ClassRoomManager { public static void main(string[] args) { ClassRoom roomone = new ClassRoom(); roomone.setroomnumber("mh227"); roomone.settotalseats(30); System.out.println("Room number: " + roomone.getroomnumber()); System.out.println("Total seats: " + roomone.gettotalseats()); This program instantiates the ClassRoom class presented in above program: Class, and invokes its methods. If we compile both classes, ClassRoom and ClassRoomManager, and execute ClassRoomManager, the following will be the output: Room number: MH227 Prepared by: A.Saleem Raja.,-Asst.Prof MCA pg. 44