Beehive College, Dehradun                      [OOP Using Java Programming]                             Notes of-Unit1st  ...
••A large collection of ready-made software components that provide many usefulcapabilities such as graphical user interfa...
This is possible due to Existence of both compiler and interpreter in JDK.With compiler, a Java program is translated into...
1) No preprocessor: Java does not require constructs such as #define, #include, and#ifdef etc2) JAVA uses 16-bit Unicode c...
Demo Applets and Applications     (In the demo subdirectory.) Examples, with source code, of programming     for the Java ...
e.g     Legal variable names are:-       temperature TEMP23 T        $temp_1    T$$1    Illegal variable names :       4.7...
Answer:- Keywords:- Keywords are the words that may seems to be legal variablenames but they are not because they are rese...
48) switch 49) true 50) cast 51) default 52) final 53) goto 54) int 55) operator 56) rest 57) synchronized 58) try Questio...
Integer                Floating                  Character                 Boolean                               pointbyte...
This stores values as 64-bit number.               double variable can store values from               (1.7 e-308) to (1.7...
// a is a reference to an interface xyz, which is being implemented by the class pc.}}Question No (9): - Explain a simple ...
int i;System.out.println (“Enter value of i”);i=KeyBoard.readInt();System.out.println (“You have entered i=”+i);}}Explanat...
But readLine() method will read and return the value as string.       We can easily convert String value into numeric valu...
1) Arithmetic Operators         Java language supports the arithmetic operators as listed below for all integer and real  ...
4) Bitwise Operators:- Can be classified into following three categories:-1. Logical2. Shift3. Assignment operatorsLogical...
Operator         Use                                Description=                op1 = op2                          Op1 = o...
A method (function) call evaluates to the return value of the method.The return data type of a method expression call is t...
x1 = (-b +d )/ (2*a)     x2 = (-b - d )/ (2*a)Question No (16):- What do you understand by Flow control ? Illustrate prope...
// statements when all above false}     c) Switch      Java has a shorthand for certain types of multiple if statements, c...
do-while Vs while : The main difference between these two is that in do-while loop theexpression is evaluated at the botto...
type[] array_name;Eg.    int[] counts;        double[] scores;        Time[] appointmentTime2. Allocate the object:-      ...
int size = 0;        public Collection (int number) {                    item = new int[number];        }public void readA...
Upcoming SlideShare
Loading in …5
×

Notes of java first unit

416 views
349 views

Published on

g r bhat

Published in: Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
416
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Notes of java first unit

  1. 1. 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) Platform b) Java platform c) Java Virtual Machine d) Java APIAnswer:- 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, garbagecollected memory heap & memory area••Every Java interpreter, whether it’s a Java development tool or a Web browser that canrun Java applets is an implementation of Java VM.d) Java Application Programming Interface (Java API)1
  2. 2. ••A large collection of ready-made software components that provide many usefulcapabilities 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 platformindependent?Answers:- Java Language features :- Java is a High-Level Programming Language thatis code can be written in simple English like language. Use of low level pneumonic isusually 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 anddifficult features.2) Objected oriented : - Java is a purely object oriented programming language. Itimplements the basic object technology of C++ with enhancement. Concepts ofencapsulation, Inheritance & polymorphism are strictly implemented by the java.In java programs even main () method must be encapsulated in some class i.e called asmain class.3) Distributed: - Java has built-in extensive TCP/IP networking capabilities, Because ofthese in-built capabilities writing distributed or network based applications is very easy injava.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 1program. Multithreading improves interactive performance and real-time behaviour.Different sections (each section is assumed as thread) of a single program may executesimultaneously because of its multi-threading feature.7) Architecture Neutral (Special Feature):- Architecture Neutrality is the specificfeature of java, that means program can be written in a machine with anysoftware/hardware architecture. This program can easily execute on a machine withdifferent architecture.2
  3. 3. 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 beimplemented on UNIX, PC & MAC environmentsQuestion No (3): - What do you understand by Java applications & Java applets? Whyjava 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 softwareplatform, we can write many types of programs.•Applets - A Java program that adheres to certain conventions that allows it to run withina 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 thatrun over the Internet.Java is important for Internet programming: - Although powerful applicationprogramming 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-orientedprogramming language, Thus difference lies in entire programming paradigm.Apart from object oriented features such as encapsulation, inheritence & polymorphismthere are also some other common differences between C & Java.3
  4. 4. 1) No preprocessor: Java does not require constructs such as #define, #include, and#ifdef etc2) JAVA uses 16-bit Unicode characters: Unicode is something similar to ASCII codesbut much more codes are available in this style than that of ASCII. Unicode arecompatible with ASCII and to the ISO8859-1 (Latin-1) characters.These are universally acceptable & codes for almost all languages are available inUnicode system.3) No pointers: Pointers are not visible to the programmers in Java. Referencing anddereferencing 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 interfaces5) Garbage Collection: in C you need to make explicit calls to malloc() to allocatememory. Use free() to deallocate memory.In Java, there is a new keyword to allocate the memory, but nothing to delete or to freethe memory. Objects are implicitly deleted when they go out of scope or are no longerneeded.Question No (5): - What do you understand by JDK? Explain objective of some commoncomponents of JDK?Answer:- Java Development Kit(JDK):- Java development kit contains variouscomponents that facilitates writing,compilation,interpretation,execution of javaapplications & 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 promptRuntime 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
  5. 5. 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 SDKs bin directory: jar xvf src.zipQuestion No (6): -What do understand by identifier? What are guidelines about thevariables? Define scope of the variables?Answer:- Identifiers/Variables:- Identifiers or variables are the symbols that representssome memory location, that can store the values.Declaration of the variable:- variable can be declare by describing the type of values thatit 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. 32 temperatureTo 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- orlowercase) that may be followed by any number (including zero) of letters & digits.5
  6. 6. 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 & lowercasevariable name: -e.gint Temp;temp=3;cause Java to give the errorUndefined variable; tempTo declare a constant value:- final double PI = 3.14159;Variable Scope:-A variables scope is the block of code within which the variable is accessible anddetermines when the variable is created and destroyed. The location of the variabledeclaration within your program establishes its scope and places it into one of these 4categories: •Member variable•Local variable•Method parameter•Exception-handler ParameterAll four categories can be illustrated as below:-Question No (7): - List the Java Keywords?6
  7. 7. Answer:- Keywords:- Keywords are the words that may seems to be legal variablenames 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) boolean12) 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) public7
  8. 8. 48) switch 49) true 50) cast 51) default 52) final 53) goto 54) int 55) operator 56) rest 57) synchronized 58) 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: - Data types in Java Derived PrimitiveNumeric Non-numeric Classes Arrays Interface 8
  9. 9. Integer Floating Character Boolean pointbyte short int long float double ong 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
  10. 10. 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 areference 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 { variables constructors 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
  11. 11. // 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 theuser? Illustrate all terms used?Answer:- Two simple ways to read a numeric value entered by the user may be asfollows:- a) Using Keyboard class: -public static void main(String args[]){String s;11
  12. 12. 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 numericvalue 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.12
  13. 13. But readLine() method will read and return the value as string. 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 rules b) Type casting.Answer: - a) Automatic type promotion rules in java: - During the various calculationsthere are chances that the final or intermediate results may exceed the limit of concerndata type. To maintain the precision of result java automatically promotes the data typesto 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 operators5. Increment/Decrement operators6. Assignment operators7. Conditional operators8. Special operators13 Operator Use Description+ op1 + op2 Adds op1 and op2- op1 - op2 Subtracts op1 from op2* op1 * op2 Multiplies op1 by op2
  14. 14. 1) Arithmetic Operators 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 themOperator Use Description> op1 > op2 Op1 is greater than op2>= op1 >= op2 Op1 is greater than or equal to op2< op1 < op2 Op1 is smaller than op2<= op1 <= op2 Op1 is smaller than or equal to op2== op1 == op2 Op1 is equal to op2!= op1 != op2 Op1 is not equal to op2 3) Logical Operators:- Relational operators are often used with logical operators to construct more complex decision-making expressions. Operat Us Descripti or e on and op2 are both op1 & op1 && conditional true, evaluates & op2 Either op1 and op2 are ly op2 | op1 || conditional true, evaluates | op2 ! ! ly is op op2 op falseand op2 are both op1 alway & op1 & evaluates true, s op2 Either op2 op1 and op2 are alway | op1 | evaluates true, s op2 op2 Shorthand for if-else The and ?: operator evaluates statement ? expression ? op1 : and returns expression op1 if it’s true and : op2 it’s op2 if false 14
  15. 15. 4) Bitwise Operators:- Can be classified into following three categories:-1. Logical2. Shift3. Assignment operatorsLogical operators–& bitwise AND| bitwise OR^ bitwise (XOR)~ bitwise complementShift operators>> shift right with sign extension>>> shift right with zero fill<< shift left with zero fllGeneral formValue << numValue >> numValue >>> numIncrement/decrement Operators+ + Increase value by 1- - Decrease value by 1Assignment OperatorsAssignment operators are used to assign one value to another. Listed below are the basicassignment operators (=) as well as the shortcut assignment operators.15
  16. 16. Operator Use Description= op1 = op2 Op1 = op2+= op1 += op2 op1 = op1 + op2-= op1 -= op2 op1 = op1 - op2*= op1 *= op2 op1 = op1 * op2/= op1 /= op2 op1 = op1 / op2%= op1 %= op2 op1 = op1 % op2&= op1 &= op2 op1 = op1 & op2|= op1 |= op2 op1 = op1 | op2 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 operators eg. temperature = 98; total = (count + 10)* 25 / 4; count++; b) Method call expression eg. Keyboard.readInt(), Integer.parseInt() 16
  17. 17. 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 returnvalue of that method.Question No (14):- What will be the output of following expressions:-a. 12 & 14 =?b. -25 >>> 3c -25 >> 3Answer:-a) 12 & 14 12 = 00000000 00000000 00000000 00001100 & AND14 = 00000000 00000000 00000000 00001110 00000000 00000000 00000000 00001100 (i.e 12)b). -25 >>> 3 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 ofthe quadratic equation as shown below ax2 + bx + c = 0Answer:- 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) ;17
  18. 18. x1 = (-b +d )/ (2*a) x2 = (-b - d )/ (2*a)Question No (16):- What do you understand by Flow control ? Illustrate proper javasyntax for following terms with the help of suitable examples? a) if-else b) if-else ladder c) switch d) while e) do while f) for loop g) break h) continueAnswer:- •Flow control – Program statements (including Java) execute in sequence onlyunless 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-elseif (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{18
  19. 19. // 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 statementsFor example, suppose that your program contained an integer named month whose valueindicated the month in some date. Suppose also that you wanted to display the name ofthe month based on its integer equivalent. You could use Javas switch statement toperform 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; 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 is12. and so on.Finally, you can use the default statement at the end of the switch to handleall values that arent explicitly handled by one of the case statementsd) while:- A while statement performs some action while a certain condition remainstrue. The general syntax of the while statement is: while (condition) statementsThat is, while condition is true, do/execute the statemente) do-while :-Java provides another loop, the do-while loop, which is similar to the while loop : do { statements19 } while (condition);
  20. 20. do-while Vs while : The main difference between these two is that in do-while loop theexpression is evaluated at the bottom of the loop, thus, the body of the loop is alwaysexecuted AT LEAST ONCE.The do-while statement is a less commonly used loop construct in programming but doeshave its uses. For example, the do-while is convenient to use when the statements withinthe 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: for (initialization; termination; increment) statementsinitialization ==> a statement that initializes the loop--its executed once at the beginningof the loop.termination ==> expression that determines when to terminate the loop. This expressionis evaluated at the top of each iteration of the loop. When the expression evaluates tofalse, the for loop terminates.increment ==> expression that gets invoked for each iteration through the loopf) break statements : The break statements cause control to break out of the switch andcontinue with the first statement following the switch. The break statements are necessarybecause case statements fall through. That is, without an explicit break control will flowsequentially through subsequent case statements. The syntax for break is:- break;g) continue: - The continue statement in the loop cause control to execute for nextiteration 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 bydeclaration & memory allocation in respect to array?Answer: - Array: - An array contains a fixed number (called its length) of variables ofidentical type.In Java, it is a specialized kind of object and it must be declared in 2 steps :1. Declare the object:20
  21. 21. type[] array_name;Eg. int[] counts; double[] scores; Time[] appointmentTime2. Allocate the object:- array_name = new type [size];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];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 objectsTo 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 illegalQuestion 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;21
  22. 22. 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(); // 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

×