Notes of java first unit

32
3 2 Beehive College, Dehradun [OOP Using Java Programming] Notes of-Unit1 st (Compiled by: Rakshanda Khan) Question No (1) : - What do you understand by following terms: - a) Platform b) Java platform c) Java Virtual Machine d) Java API Answer :- a) Platform –The term platform in respect to programming language refers to the hardware & software environment in which a program of that language runs. e.g. If one wants to run program written in C, a specific hardware as well as TC environment ( i.e. a software) are required. Program will execute if and only if TC is available on target machine. b) Java platform – Java programs are assumed as platform independent, that means program may be written in any software/hardware environment as well as program written on one machine can execute on any other machine without installing complete JDK. Although to run java programs complete JDK is not required yet some minimum specific software must available on the machine, this software-only platform that runs on top of other, hardware-based platforms is called as Java platform. The Java platform has 2 components : - 1) Java Virtual Machine (Java VM): - JVM refers to a virtual CPU including instruction set, register set, class file format, stack, garbage collected memory heap & memory area. 1

description

g r bhat

Transcript of Notes of java first unit

Page 1: Notes of java first unit

Beehive College, Dehradun[OOP Using Java Programming]

Notes of-Unit1st

(Compiled by: Rakshanda Khan)

Question No (1): - What do you understand by following terms: -a) Platformb) Java platformc) Java Virtual Machined) Java API

Answer :- a) Platform –The term platform in respect to programming language refers to the

hardware & software environment in which a program of that language runs.e.g. If one wants to run program written in C, a specific hardware as well as TC environment ( i.e. a software) are required. Program will execute if and only if TC is available on target machine.

b) Java platform – Java programs are assumed as platform independent, that means program may be written in any software/hardware environment as well as program written on one machine can execute on any other machine without installing complete JDK.

Although to run java programs complete JDK is not required yet some minimum specific software must available on the machine, this software-only platform that runs on top of other, hardware-based platforms is called as Java platform.

The Java platform has 2 components: -

1) Java Virtual Machine (Java VM): - JVM refers to a virtual CPU including instruction set, register set, class file format, stack, garbage collected memory heap & memory area. Every java interpreter, whether it’s a java development tool or a web browser that can run java applets is an implementation of java VM.

It means java interpreter or java enabled web browser can work only if JVM software is installed in target machine.

2) Java Application Programming Interface (Java API): - JAVA API refers to a large collection of ready-made software components that provide many useful capabilities such as graphical user interface (GUI) widgets. The Java API is grouped into libraries (packages) of related components. Examples of Java API are AWT, Swings, Java Beans and Networking API etc.

c) Java Virtual Machine (Java VM)••A virtual CPU including instruction set, register set, class file format, stack, garbage collected memory heap & memory area••Every Java interpreter, whether it’s a Java development tool or a Web browser that can run Java applets is an implementation of Java VM.

d) Java Application Programming Interface (Java API)

1

Page 2: Notes of java first unit

••A large collection of ready-made software components that provide many useful capabilities such as graphical user interface (GUI) widgets.••The Java API is grouped into libraries (packages) of related components••Examples of Java API are AWT, Swing, Java Beans and Networking API etc.

Question No (2): - Explain common features of Java language? How java is platform independent? Answers:- Java Language features :- Java is a High-Level Programming Language that is code can be written in simple English like language. Use of low level pneumonic is usually not expected by the programmers. Following are the common features of Java: - 1) Simple : - Java is language with powerful functionality without the confusing features (e.g. pointers). More than 50% bugs are reduced because of not using confusing and difficult features.

2) Objected oriented : - Java is a purely object oriented programming language. It implements the basic object technology of C++ with enhancement. Concepts of encapsulation, Inheritance & polymorphism are strictly implemented by the java.In java programs even main () method must be encapsulated in some class i.e called as main class.

3) Distributed : - Java has built-in extensive TCP/IP networking capabilities, Because of these in-built capabilities writing distributed or network based applications is very easy in java.

4) Robust:- Java is a robust in nature, In java Problems are checked at compile and run-time.

It can catch the bugs at the early stage of development. Java handles own memory; programmers are not required to worry about freeing

memory or dealing with corrupting memory. In built garbage collection & memory optimization features of java automatically help in memory management.

Java reduces development time as there is no need to write exhaustive code related with memory management, optimization etc. Moreover different sections of a single program may execute simultaneously because of its multi-threading feature.

5) Secure: - Java is a secure language as Java codes passes several tests before executing on machine eg. Byte-code verifier, class loader etc.

6) Multithreaded : - Threads are light-weighted processes that allow many simultaneous activities in 1 program. Multithreading improves interactive performance and real-time behaviour. Different sections (each section is assumed as thread) of a single program may execute simultaneously because of its multi-threading feature.

7) Architecture Neutral (Special Feature):- Architecture Neutrality is the specific feature of java, that means program can be written in a machine with any software/hardware architecture. This program can easily execute on a machine with different architecture.

2

Page 3: Notes of java first unit

This is possible due to Existence of both compiler and interpreter in JDK. With compiler, a Java program is translated into Java bytecodesWith interpreter, each Java byte code instruction is parsed and run on computers.Interpreter first modifies the byte code according to architecture of target machine.

8) Portable: -Being architecture neutral / independent Java is highly portable. Java builds its user interfaces via an abstract window system so the windows can be implemented on UNIX, PC & MAC environments

Question No (3): - What do you understand by Java applications & Java applets? Why java is important for Internet programming?

Answer:- Java programs can be categorized into two groups:- Applications:- A standalone Java program that runs directly on a javaplatform. Java application programs are something similar to that of common C/C++ programs. As Java is a general purpose, high-level programming language and a powerful software platform, we can write many types of programs.

•Applets - A Java program that adheres to certain conventions that allows it to run within a Java-enabled web browser. In other words Applets can be defined as interactive or non-interactive GUI Interfaces/windows etc. Applets may be embedded with web pages that run over the Internet.

J ava is important for Internet programming : - Although powerful application programming is possible in java, yet java is mostly preferred because of its applets.Java is termed as “boon for the internet programming”. Features and capabilities of WebPages may drastically enhanced with the help of applets

Applets may be written for any purpose including visual, graphical or interactivity etc.

Because of Architecture Neutral feature of java, applets written on one machine may load & execute on any other machine in the world.

Because of Unicode character style feature of java applets may be written for any language and are universally accepted.

Only JVM must install on the target machine to execute the applets, complete J2SDK is not required.

Additional provisions such as .jar files etc helps in fast loading of Applets.

Therefore due to strong capabilities of applets, architectural neutral feature of java & universal acceptance due to Unicode style, java is important for Internet programming.

Question No (4): - List the 5 differences between Java and C?

Answer:- C is a procedural language whereas Java is a purely object-oriented programming language, Thus difference lies in entire programming paradigm. Apart from object oriented features such as encapsulation, inheritence & polymorphism there are also some other common differences between C & Java.

3

Page 4: Notes of java first unit

1) No preprocessor: Java does not require constructs such as #define, #include, and #ifdef etc

2) JAVA uses 16-bit Unicode characters: Unicode is something similar to ASCII codes but much more codes are available in this style than that of ASCII. Unicode are compatible with ASCII and to the ISO8859-1 (Latin-1) characters. These are universally acceptable & codes for almost all languages are available in Unicode system.

3) No pointers: Pointers are not visible to the programmers in Java. Referencing and dereferencing of objects are handled automatically by JAVA.

4) No multiple inheritances: JAVA does not support multiple inheritances; features of multiple inheritances are supported in the form of interfaces

5) Garbage Collection: in C you need to make explicit calls to malloc() to allocate memory. Use free() to deallocate memory. In Java, there is a new keyword to allocate the memory, but nothing to delete or to free the memory. Objects are implicitly deleted when they go out of scope or are no longer needed.

Question No (5): - What do you understand by JDK? Explain objective of some common components of JDK?Answer:- Java Development Kit (JDK):- Java development kit contains various components that facilitates writing,compilation,interpretation,execution of java applications & applets. JDK is also called as J2SDK (java 2 standard development Kit). Common components of JDK/J2SDK are: -

Development Tools (In the bin subdirectory.) Tools and utilities that will help you to develop, execute, debug, and document programs written in the Java programming language. e,g:-javac:- (java compiler) that compiles the source code & prepares bytecode for that program.java:- (java interpreter) that interprets the bytecode code on target machine.javah: is used to include c header files in java programs.appletviewer: - is used to test the applet from command prompt

Runtime Environment (In the jre subdirectory.) An implementation of the Java 2 runtime environment for use by the SDK. The runtime environment includes a Java virtual machine, class libraries, and other files that support the execution of programs written in the Java programming language.

Additional Libraries (In the lib subdirectory.) Additional class libraries and support files required by the development tools.

4

Page 5: Notes of java first unit

Demo Applets and Applications (In the demo subdirectory.) Examples, with source code, of programming for the Java platform. These include examples that use Swing and other Java Foundation Classes, and the Java Platform Debugger Architecture.

C header Files (In the include subdirectory.) Header files that support native-code programming using the Java Native Interface, the Java Virtual Machine Debugger Interface, the Java Virtual Machine Profiler Interface and other functionality of the Java 2 Platform.

Source Code (In src.zip.) Java programming language source files for all classes that make up the Java 2 core API (that is, sources files for the java.*, javax.* and some org.* packages, but not for com.sun.* packages). This source code is provided for informational purposes only, to help developers learn and use the Java programming language. These files do not include platform-specific implementation code and cannot be used to rebuild the class libraries. To extract these file, one can use any common zip utility. Or, may use the Jar utility in the Java 2 SDK's bin directory: jar xvf src.zip

Question No (6): -What do understand by identifier? What are guidelines about the variables? Define scope of the variables? Answer:- I dentifiers/Variables:- Identifiers or variables are the symbols that represents some memory location, that can store the values.Declaration of the variable:- variable can be declare by describing the type of values that it is intended to store.e.g.int temperature; // The Fahrenheit temperatureThink of variable like a container for a value:

temperature = 32; // temperature contains the value 32The above is an assignment statement and “=“ is the assignment operator.

temperature

To declare more than 1 variable, all variable of same type must be written in a line:e.g.int fahrTemp, centTemp;int is the type name for variables fahrTemp as well as for centTemp.

Legal Identifiers/Variables:- Legal variable name must consists of a letter (upper- or lowercase) that may be followed by any number (including zero) of letters & digits.

5

Page 6: Notes of java first unit

e.g Legal variable names are:- temperature TEMP23 T $temp_1 T$$1 Illegal variable names : 4.7 !%--

Java is case sensitive that means it differentiates between uppercase & lowercase variable name: -e.gint Temp;temp=3;cause Java to give the errorUndefined variable; temp

To declare a constant value:-

final double PI = 3.14159;

Variable Scope:-

A variable's scope is the block of code within which the variable is accessible and determines when the variable is created and destroyed. The location of the variable declaration within your program establishes its scope and places it into one of these 4 categories: •Member variable •Local variable •Method parameter •Exception-handler Parameter All four categories can be illustrated as below:-

Question No (7): - List the Java Keywords?

6

Page 7: Notes of java first unit

Answer:- Keywords:- Keywords are the words that may seems to be legal variable names but they are not because they are reserved by the language for special uses.

List of Keywords in Java:- Following are the keywords in java:-1) abstract2) catch3) do4) finally5) if6) interface7) outer8) return9) this10) var11) boolean 12) char13) double14) float15) implements16) long17) package18) short19) throw20) void21) break22) class23) else24) for25) import26) native27) private28) static29) throws30) volatile31) byte32) const33) extends34) future35) inner36) new37) protected38) sure39) transient40) while41) case42) continue43) false44) generic45) instanceof46) null47) public

7

Page 8: Notes of java first unit

48) switch49) true50) cast51) default52) final53) goto54) int55) operator56) rest57) synchronized58) try

Question No (8): - What do you understand by data type? Illustrate various data types available in java?Answer:- Data Type:- Data type refers to category of the variable, based on which certain explicit characteristics such as range of the values that can be stored by the variable, number of bits required to represent the value etc of the variable may be explained. Java language is rich in its data types. The variety of data types available allows the programmer to select the type appropriate to the needs of the application.Data types in java may be classified in the two major categories:-a) Primitive (Built in types) b) Reference / Object (Derived Types)

Above types are further classified as shown below: -

8

Data types in Java

Primitive Derived

Numeric Non-numeric Classes Arrays

Interface

Page 9: Notes of java first unit

a) Primitive Data types:- Primitive data types are those that are in-built defined by the java, user can not change characteristics of the primitive data types, e.g. int, float, char etc.

Primitive data types are further classified into two categories: -1) Numeric 2) Non-Numeric

1) Numeric : - Numeric data type refers to those variables that can store only arithmetic values not character values. Numeric data types are further classified into two sub-categories:-

Integer : - Integer variables refer to the variables that can store arithmetic values without decimal portion. Integer variables are of four types: -byte: - This is the smallest type of integer variables. Byte variable can store value from –128 to 127. This stores values as 8-bit binary number.

short :- short type variable can store values from (-2^15) to (2^15-1)

This stores values as 16-bit binary number.

int :- Most common type of integer. int variable can store values from

(-2^31) to (2^31-1) This stores values as 32-bit binary number.

long:- longest type of integer variables. long variable can store values from

(-2^63) to (2^63-1) This stores values as 64-bit binary number.

Float :- Float variables refer to those variables that can store arithmetic values

with decimal portion. Float variables are of two types: -float:- float variables are having precision of 6 digits after the decimal. This stores values as 32-bit number.

float variable can store values from (3.4e-038) to (3.4e+038)In default all initialization to float variables are promoted to double.If one wants to assign that as float only, literal f must be used after value.

double: - double variables are having precision of 12 digits(i.e double that of float) after the decimal.

9

Integer Floating Character Boolean

byte short longint

float double

Page 10: Notes of java first unit

This stores values as 64-bit number.double variable can store values from (1.7 e-308) to (1.7e+308)

2) Non-Numeric : - Non-Numeric data type refers to those variables that can store

only non-arithmetic values. boolean: -Java has a simple type, called boolean, for logical values. It can have

only one of two possible values, true or false.

char:- In java, the data type used to store characters is char, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages. For this purpose, it requires 16 bits. Thus in java char is a 16-bit type. The range of char is 0 to 65536. There are no negative chars.

b) Derived data type/Reference types:-The value of a reference type variable is a reference to the actual value or set of values represented by the variable.

Classes: - Classes are the templates for creating objects.Example – class references class A {

variablesconstructors

methods } A a = new A( ) //a is a reference to an object of class A

Arrays Example – Array references int myArray [ ] = new int [4];

Interfaces Example – Interface references interface xyz { public void pc(); }

class A implements pc { public void pc() { System.out.println(“Hello”); } }

class prog {public static void main(String args[]){xyz a = new pc();

10

Page 11: Notes of java first unit

// a is a reference to an interface xyz, which is being implemented by the class pc.}}

Question No (9): - Explain a simple program in java to print some message on screen? Illustrate all terms used?

Answer: - The first simple program in java may be as follows: -class prog1 {public static void main(String args[]){System.out.println (“first program in java”);}}

Important Points: - 1) The class that contain the main method is termed as main class. 2) The name of main class must be the same as that of file in which program is saved.

3) The java file must be stored with .java extension.4) The term public refers that method main is accessible from outside the class

prog1 also.5) The term static refers that main is static method. Static methods are those method

that we can call without creating their objects.6) The term void refers to the method will return nothing.7) The term String args[] indicates that args[] is an array of string type. Since we are

using as parameter to main method, therefore it will store all parameters that will be entered from the command prompt.

8) System.out.println(“first program in java”); The println is a method accept string parameter to display at screen. pintln is the static method, definition of this method is given in the out class which in turn is the inner class of System class.

Question No (10): - Explain two ways for reading some numeric value entered by the user? Illustrate all terms used?Answer:- Two simple ways to read a numeric value entered by the user may be as follows:-

a) Using Keyboard class : -

public static void main(String args[]){String s;

11

Page 12: Notes of java first unit

int i;System.out.println (“Enter value of i”);i=KeyBoard.readInt();System.out.println (“You have entered i=”+i); }}

Explanation:-This is the simplest procedure to read the integer value entered by the user.The method readInt() which is static in nature & defined in class KeyBoard will accept & return the numeric value entered through the keyboard.But to use this procedure KeyBoard class must available in java library.

b) Using BufferedReader class:- import java.io.*;import java.lang.*;class prog3 {public static void main(String args[]){String s;int i;BufferedReader br = new BufferedReader (new InputStreamReader (System. in));System.out.println (“Enter value of i”);s=br.readLine();i=Integer.parseInt(s);System.out.println (“You have entered i=”+i); }}

Explanation: - This the most powerful but little bit difficult procedure to read numeric value entered by the user.

System.in indicates that in class is the inner class of System class. The term System.in indicates that some default method that exists inside the in

class is invoked. Whenever user enters any numeric value that will store in keyboard buffer This default method will read value as bit stream from the keyboard buffer. The constructor InputStreamReader(System.in) takes that bit stream as parameter

to this constructor. The constructor InputStreamReader(System.in) will convert the bit stream into

string.

The term BufferedReader br = new BufferedReader (value) indicates that an object br of BufferedReader type is created that will store the value

Obviously BufferedReader br = new BufferedReader (new InputStreamReader (System. in));

Will result in storage of value in br object.

From br object we can read value with the help of readLine() method that is defined in BufferedReader class.

But readLine() method will read and return the value as string.

12

Page 13: Notes of java first unit

Operator Use Description

+ op1 + op2 Adds op1 and op2

- op1 - op2 Subtracts op1 from op2

* op1 * op2 Multiplies op1 by op2

/ op1 / op2 DIvide op1 by op2

% op1 % op2 The remainder of dividing op1 by op2

We can easily convert String value into numeric value with the help of Wrapper classes such as Integer.

ParseInt is the static method that convert String value into numeric value.

Question No (11): - Explain following terms in respect to data types in java?a) Automatic type promotion rulesb) Type casting.

Answer: - a) Automatic type promotion rules in java: - During the various calculations there are chances that the final or intermediate results may exceed the limit of concern data type. To maintain the precision of result java automatically promotes the data types to upper data type. Some common type promotion rules are:-

1) All assignments to float variable results in promotion of the assignment as double, unless you are writing f literal as suffix at end of the value.

2) All byte and short values are promoted to int.3) If any one operand is long, the whole expression is promoted to long.4) If any one operand is float, the whole expression is promoted to float.5) If any one operand is double, the whole expression is promoted to double.

b) Type casting:- Although the automatic type promotions are helpful, they will not fulfill all needs. To create a conversion between two data types if the destination type is smaller than the source data type, we use the concept of cast. A cast is simply an explicit type conversion. It has the general form: - (target type) value.

e.g. byte a;byte b;byte c = a * b; above statement is wrong as a*b will be promoted to int. If we want to store this int result as byte value in c, we must use casting as.byte c =(byte) (a*b);

Question No (12): - Categories the various operators available in Java?Answer: - Java supports a rich set of operators that can be classified into six categories:-1. Arithmetic operators2. Relational operators3. Logical operators4. Bitwise operators 5. Increment/Decrement operators6. Assignment operators7. Conditional operators8. Special operators

1) Arithmetic Operators

13

Page 14: Notes of java first unit

Operator

Use

Description

&&

op1 && op2

op1 and op2 are both true,conditionally

evaluates op2

||

op1 || op2

Either op1 and op2 are true,conditionally

evaluates op2! !

opop is false

& op1 & op2

op1 and op2 are both true,

alwaysevaluates

op2| op1 |

op2

Either op1 and op2 are true,

alwaysevaluates

op2

?:

expression ? op1 : op2

Shorthand for and

if-else statementThe ?: operator evaluates

expressionand returns op1 if it’s true and op2 ifit’s false

Java language supports the arithmetic operators as listed below for all integer and real numbers:

2). Relational:-A relational operator compares 2 values and determines the relationship between them

3) Logical Operators:-Relational operators are often used with logical operators to construct more complex decision-making expressions.

14

Page 15: Notes of java first unit

4) Bitwise Operators:- Can be classified into following three categories:-1. Logical2. Shift3. Assignment operators

Logical operators–& bitwise AND| bitwise OR^ bitwise (XOR)~ bitwise complement

Shift operators>> shift right with sign extension>>> shift right with zero fill<< shift left with zero fllGeneral formValue << numValue >> numValue >>> num

Increment/decrement Operators+ + Increase value by 1- - Decrease value by 1

Assignment OperatorsAssignment operators are used to assign one value to another. Listed below are the basic assignment operators (=) as well as the shortcut assignment operators.

15

Page 16: Notes of java first unit

Question No (13): - What do you understand by the expressions?Answer:-Definition:-An expression is a series of variables,operators and method calls (constructed according to the syntax of the language) that evaluates to a single value.

Expressions perform the work of a Java program.•Expressions are used to:• Compute (eg. totalPrice = productCost + shippingCost) • Assign values to variables (eg. count = 10)• To help control the execution flow of a program (eg while (count <10) count++;)

Type of Expressions: -Basically, there are 2 types of expressions:a) Expression with operatorseg.temperature = 98;total = (count + 10)* 25 / 4; count++;

b) Method call expressioneg. Keyboard.readInt(), Integer.parseInt()

A method (function) call evaluates to the return value of the method.The return data type of a method expression call is the same as the data type of the return value of that method.

Question No (14):- What will be the output of following expressions:-a. 12 & 14 =?b. -25 >>> 3c -25 >> 3

Answer:- a) 12 & 14 12 = 00000000 00000000 00000000 00001100 & AND14 = 00000000 00000000 00000000 00001110 00000000 00000000 00000000 00001100

(i.e 12)

b). -25 >>> 3

16

Page 17: Notes of java first unit

25 = 00000000 00000000 00000000 00011001

-25 = 11111111 11111111 11111111 11100111>>>3 00011111 11111111 11111111 11111100

(i.e 536870908 )

c). -25 >> 3

25 = 00000000 00000000 00000000 00011001

-25 = 11111111 11111111 11111111 11100111>>3 11111111 11111111 11111111 11111100

(i.e -4 )

Question No (15 ): -.Write an expression that returns the solution for the general form of the quadratic equation as shown below

ax2 + bx + c = 0

Answer:- The typical expressions for the roots x1 & x2 may be as given below:-

double d , x1, x2, b, a, c; d= Math.sqrt (b*b-4*a*c) ; x1 = (-b +d )/ (2*a) x2 = (-b - d )/ (2*a)

Question No (16):- What do you understand by Flow control ? Illustrate proper java syntax for following terms with the help of suitable examples?

a) if-elseb) if-else ladder c) switchd) whilee) do whilef) for loopg) breakh) continue

Answer:- •Flow control – Program statements (including Java) execute in sequence only unless a flow control permits the change of the default sequential flow.

The typical syntax for above given sequential / iteration term are as follows: -

a) if-else

17

Page 18: Notes of java first unit

if (conditional expression) {

// statements when true }else{

// statements when false }

b) if-else ladder:- if (conditional expression no 1 ) {

// statements when true }

else if (conditional expression no 2) {

// statements when true }

else if (conditional expression no 3) {

// statements when true }

- - - - - - - - - - - - - - - - - - - - - - - -

else{

// statements when all above false }

c) Switch Java has a shorthand for certain types of multiple if statements, called the switch-case statement. In certain situations, the switch-case statement will be much more effective than multiple if statements

For example, suppose that your program contained an integer named month whose value indicated the month in some date. Suppose also that you wanted to display the name of the month based on its integer equivalent. You could use Java's switch statement to perform this feat:

int month; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break;

18

Page 19: Notes of java first unit

case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; default: }case 1 refers to if the value of month is 1, similarly case 12 means if the value of month is 12. and so on.Finally, you can use the default statement at the end of the switch to handle all values that aren't explicitly handled by one of the case statements

d) while:- A while statement performs some action while a certain condition remains true. The general syntax of the while statement is:

That is, while condition is true, do/execute the statement

e) do-while :- Java provides another loop, the do-while loop, which is similar to the while loop :

do-while Vs while : The main difference between these two is that in do-while loop the expression is evaluated at the bottom of the loop, thus, the body of the loop is always executed AT LEAST ONCE.

The do-while statement is a less commonly used loop construct in programming but does have its uses. For example, the do-while is convenient to use when the statements within the loop must be executed at least once

e) for :- One must use the for loop when one know the constraints of the loop (its initialization instruction, termination criteria, and increment instruction).

The general form of the for statement can be expressed like this:

19

for (initialization; termination; increment) statements

do { statements } while (condition);

Page 20: Notes of java first unit

initialization ==> a statement that initializes the loop--its executed once at the beginning of the loop. termination ==> expression that determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates to false, the for loop terminates. increment ==> expression that gets invoked for each iteration through the loop

f) break statements : The break statements cause control to break out of the switch and continue with the first statement following the switch. The break statements are necessary because case statements fall through. That is, without an explicit break control will flow sequentially through subsequent case statements.

The syntax for break is:- break;

g) continue: - The continue statement in the loop cause control to execute for next iteration ignoring the remaining portion of the loop.

The syntax for continue is:- continue;

Question No (17):- Define Array in Java? Explain what do you understand by declaration & memory allocation in respect to array?Answer: - Array: - An array contains a fixed number (called its length) of variables of identical type. In Java, it is a specialized kind of object and it must be declared in 2 steps :

1. Declare the object:

Eg. int[] counts; double[] scores; Time[] appointmentTime

2. Allocate the object:-

Eg. counts= new int[10]; scores= new double[15]; appointmentTime = new Time[10];

Combination of 2 steps may also be given in one line: type [] array_name = new type [size];

Eg. int counts= new int[10];

20

array_name = new type [size];

Page 21: Notes of java first unit

The bracketed no. is the length (which states how many variables in each array.

Array Features To Be Noted:

Arrays can contain any type of value : simple values or references to objects

To obtain a specific variable, we use subscripts,

Array subscripts can be expression, not just constant. Eg.counts[1] // constant array subscriptcounts[i]counts[i*2] counts[i/2]

Arrays can be initialized by giving a list of all their elements:int[] primes = { 2,3,5,9,11,13,17,19,23,29 };However, this can only be used at the time the array is declared. Thusint[] prime;primes = { 2,3,5,9,11,13,17,19,23,29 };is illegal

Question No (18): - What do you understand by Collection class in respect to array? Illustrate with suitable example?Answer:- Collection class:- This is a standard class that encapsulate the reading & echoing of an array entered by user through the keyboard.

The class definition of Collection class is as below:-

class Collection { int[] item; int size = 0; public Collection (int number) { item = new int[number]; }

public void readAndEcho () { // Input up to 'number' numbers System.out.print("Enter first number: "); int n = Keyboard.readInt(); while (!Keyboard.eof()) { // The first size inputs are stored in item[0] .. item[size-1] item[size] = n; size++; System.out.print("Enter next number: "); n = Keyboard.readInt(); } System.out.println();

21

Page 22: Notes of java first unit

// Print numbers, one per line for (int i=0; i<size; i++) System.out.println(item[size-i]); }}

The Collection class can be used in following manner.

class ReadAndEcho { static final int INPUT_MAX = 1000; public static void main (String[] arg) { Collection c = new Collection(INPUT_MAX); c.readAndEcho(); }}Above will result in reading & echoing of an array with 1000 values.

22