SlideShare una empresa de Scribd logo
1 de 22
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 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
••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
This is possible due to Existence of both compiler and interpreter in JDK.
With compiler, a Java program is translated into Java bytecodes
With 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 java
platform. 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.

Java 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
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
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:- Identifiers/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 temperature
Think of variable like a container for a value:

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




                       32
                   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
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.g
int Temp;
temp=3;
cause Java to give the error
Undefined 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
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) abstract
2) catch
3) do
4) finally
5) if
6) interface
7) outer
8) return
9) this
10) var
11) boolean
12) char
13) double
14) float
15) implements
16) long
17) package
18) short
19) throw
20) void
21) break
22) class
23) else
24) for
25) import
26) native
27) private
28) static
29) throws
30) volatile
31) byte
32) const
33) extends
34) future
35) inner
36) new
37) protected
38) sure
39) transient
40) while
41) case
42) continue
43) false
44) generic
45) instanceof
46) null
47) public
7
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
               Primitive



Numeric                Non-numeric                      Classes               Arrays

                                                               Interface


 8
Integer                Floating                  Character                 Boolean
                               point
byte      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
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
    {
                     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
// 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
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.

12
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 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 operators
2.    Relational operators
3.    Logical operators
4.    Bitwise operators
5.    Increment/Decrement operators
6.    Assignment operators
7.    Conditional operators
8.    Special operators




13
 Operator          Use                             Description
+                  op1 + op2                       Adds op1 and op2
-                  op1 - op2                       Subtracts op1 from op2
*                  op1 * op2                       Multiplies op1 by op2
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 them
Operator              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
4) Bitwise Operators:- Can be classified into following three categories:-
1. Logical
2. Shift
3. 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 fll
General form
Value << num
Value >> num
Value >>> num

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

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




15
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
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 >>> 3
c -25 >> 3

Answer:-
a) 12 & 14
 12 = 00000000 00000000 00000000 00001100
 &                 AND
14 = 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 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) ;

17
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-else
   b) if-else ladder
   c) switch
   d) while
   e) do while
   f) for loop
   g) break
   h) 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

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
{
18
// 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;
       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:

                     while (condition)
                     statements

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 {
                                   statements
19                               } while (condition);
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:
                  for (initialization; termination; increment)
                                   statements


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:
20
type[] array_name;

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

2. 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 objects

To obtain a specific variable, we use subscripts,

Array subscripts can be expression, not just constant.
Eg.
counts[1]      // constant array subscript
counts[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. Thus
int[] 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;
21
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

Más contenido relacionado

La actualidad más candente

Software reliability & quality
Software reliability & qualitySoftware reliability & quality
Software reliability & qualityNur Islam
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
REQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGREQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGSaqib Raza
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |ShubhamAthawane
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)Jadavsejal
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Software engineering a practitioners approach 8th edition pressman solutions ...
Software engineering a practitioners approach 8th edition pressman solutions ...Software engineering a practitioners approach 8th edition pressman solutions ...
Software engineering a practitioners approach 8th edition pressman solutions ...Drusilla918
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECSreedhar Chowdam
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQLAdil Mehmoood
 
Software Engineering - Ch1
Software Engineering - Ch1Software Engineering - Ch1
Software Engineering - Ch1Siddharth Ayer
 
Software Engineering Layered Technology Software Process Framework
Software Engineering  Layered Technology Software Process FrameworkSoftware Engineering  Layered Technology Software Process Framework
Software Engineering Layered Technology Software Process FrameworkJAINAM KAPADIYA
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java ProgrammingRavi Kant Sahu
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSaba Ameer
 

La actualidad más candente (20)

Software reliability & quality
Software reliability & qualitySoftware reliability & quality
Software reliability & quality
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Core java slides
Core java slidesCore java slides
Core java slides
 
REQUIREMENT ENGINEERING
REQUIREMENT ENGINEERINGREQUIREMENT ENGINEERING
REQUIREMENT ENGINEERING
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
what is java?
  what is java?  what is java?
what is java?
 
Java
JavaJava
Java
 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |
 
Java Development Kit (jdk)
Java Development Kit (jdk)Java Development Kit (jdk)
Java Development Kit (jdk)
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Software engineering a practitioners approach 8th edition pressman solutions ...
Software engineering a practitioners approach 8th edition pressman solutions ...Software engineering a practitioners approach 8th edition pressman solutions ...
Software engineering a practitioners approach 8th edition pressman solutions ...
 
Applet programming
Applet programming Applet programming
Applet programming
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
Software Engineering - Ch1
Software Engineering - Ch1Software Engineering - Ch1
Software Engineering - Ch1
 
Linker and Loader
Linker and Loader Linker and Loader
Linker and Loader
 
Software Engineering Layered Technology Software Process Framework
Software Engineering  Layered Technology Software Process FrameworkSoftware Engineering  Layered Technology Software Process Framework
Software Engineering Layered Technology Software Process Framework
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 

Similar a Notes of java first unit

java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docxvikasbagra9887
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxSuganthiDPSGRKCW
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java SlidesVinit Vyas
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1Qualys
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1RubaNagarajan
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxDrPreethiD1
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01Jay Palit
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to JavaDevaKumari Vijay
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Mr. Akaash
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkMohit Belwal
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 

Similar a Notes of java first unit (20)

Java ms harsha
Java ms harshaJava ms harsha
Java ms harsha
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
Java chapter 1
Java   chapter 1Java   chapter 1
Java chapter 1
 
java introduction.docx
java introduction.docxjava introduction.docx
java introduction.docx
 
Unit1 JAVA.pptx
Unit1 JAVA.pptxUnit1 JAVA.pptx
Unit1 JAVA.pptx
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
Core Java Slides
Core Java SlidesCore Java Slides
Core Java Slides
 
Java Intro
Java IntroJava Intro
Java Intro
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1
 
Features of java unit 1
Features of java unit 1Features of java unit 1
Features of java unit 1
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
Java presentation
Java presentationJava presentation
Java presentation
 
JAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptxJAVA ALL 5 MODULE NOTES.pptx
JAVA ALL 5 MODULE NOTES.pptx
 
What is-java
What is-javaWhat is-java
What is-java
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
130700548484460000
130700548484460000130700548484460000
130700548484460000
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 

Último

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 

Último (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 

Notes of java first unit

  • 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 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
  • 2. ••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
  • 3. This is possible due to Existence of both compiler and interpreter in JDK. With compiler, a Java program is translated into Java bytecodes With 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 java platform. 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. Java 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
  • 4. 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
  • 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 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:- Identifiers/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 temperature Think of variable like a container for a value: temperature = 32; // temperature contains the value 32 The above is an assignment statement and “=“ is the assignment operator. 32 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
  • 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 & lowercase variable name: - e.g int Temp; temp=3; cause Java to give the error Undefined 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
  • 7. 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) abstract 2) catch 3) do 4) finally 5) if 6) interface 7) outer 8) return 9) this 10) var 11) boolean 12) char 13) double 14) float 15) implements 16) long 17) package 18) short 19) throw 20) void 21) break 22) class 23) else 24) for 25) import 26) native 27) private 28) static 29) throws 30) volatile 31) byte 32) const 33) extends 34) future 35) inner 36) new 37) protected 38) sure 39) transient 40) while 41) case 42) continue 43) false 44) generic 45) instanceof 46) null 47) public 7
  • 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 Primitive Numeric Non-numeric Classes Arrays Interface 8
  • 9. Integer Floating Character Boolean point byte 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. 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 { 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. // 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
  • 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 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. 12
  • 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 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 operators 2. Relational operators 3. Logical operators 4. Bitwise operators 5. Increment/Decrement operators 6. Assignment operators 7. Conditional operators 8. Special operators 13 Operator Use Description + op1 + op2 Adds op1 and op2 - op1 - op2 Subtracts op1 from op2 * op1 * op2 Multiplies op1 by op2
  • 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 them Operator 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. 4) Bitwise Operators:- Can be classified into following three categories:- 1. Logical 2. Shift 3. 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 fll General form Value << num Value >> num Value >>> num Increment/decrement Operators + + Increase value by 1 - - Decrease value by 1 Assignment Operators Assignment operators are used to assign one value to another. Listed below are the basic assignment operators (=) as well as the shortcut assignment operators. 15
  • 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. 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 >>> 3 c -25 >> 3 Answer:- a) 12 & 14 12 = 00000000 00000000 00000000 00001100 & AND 14 = 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 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) ; 17
  • 18. 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-else b) if-else ladder c) switch d) while e) do while f) for loop g) break h) 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 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 { 18
  • 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 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; 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: while (condition) statements 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 { statements 19 } while (condition);
  • 20. 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: for (initialization; termination; increment) statements 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: 20
  • 21. type[] array_name; Eg. int[] counts; double[] scores; Time[] appointmentTime 2. 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 objects To obtain a specific variable, we use subscripts, Array subscripts can be expression, not just constant. Eg. counts[1] // constant array subscript counts[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. Thus int[] 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; 21
  • 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