Unit 1
Q1 Explain features of Java.
         Java was created by a team of programmers at sun micro System in 1991.it took
         18 months to develop the first working version.This Language was initially called
         “oak” but it was renamed “java” in 1995.
     What is Java?
     Java is a programming language used to develop software applications as well as
     applets that run on webpages.
     •         Java is a high level language - Java's syntax allows for the use of words and
     commands instead of just symbols and numbers, it is closer to human languages and
     further from machine language. The advantage to Java being a high level language is
     that it is easier to read, write, and maintain.
     •         Java is an object oriented language - Define your own reusable
     data structures called objects as well as their attributes
     (properties) and things they can do (methods). You can also create relationships
     between various objects and data structures.
     •         Java is a software development language AND a web language - Create
     programs and applets (small programs that run on webpages).
     •         Java is platform independent - You can run the same Java programs on various
     operating systems without having to rewrite the code, unlike other programming
     languages such as C and C++. Java source code is not converted into machine
     language, but into a special form of instruction known as Java byte code which is
     then interpreted by the Java run-time environment which instructs the operating
     system on what to do. This allows Java programs to run the same way on all operating
     systems.
     Java file extensions
     Java source code files have a .java extension. Java programs have a .class extension.
Q2 Characteristics of Java
            1. Java is simple
            2. Java is object-oriented
            3. Java is distributed
            4. Java is interpreted
            5. Java is robust
            6. Java is secure
            7. Java is architecture-neutral
            8. Java is portable
            9. Java’s performance
            10. Java is multithreaded
            11. Java is dynamic
Q3 What is Java Virtual Machine
           Java is compiled into bytecodes
           Bytecodes are high-level, machine-independent instructions for a hypothetical
            machine, the Java Virtual Machine (JVM)
           The Java run-time system provides the JVM
           The JVM interprets the bytecodes during program execution
           Since the bytecodes are interpreted, the performance of Java programs slower
            than comparable C/C++ programs
           But the JVM is continually being improved and new techniques are achieving
            speeds comparable to native C++ code
Q4 Explain JAVA Data type
                                 Java data types                     Size   in
 Keyword         Type of data the variable will store           memory
 boolean   true/false value                                 1 bit
 byte      byte size integer                                8 bits
 char      a single character                               16 bits
           double precision floating point decimal number
 double                                                     64 bits
           single precision floating point decimal number
 float                                                      32 bits
 int       a whole number                                   32 bits
 long      a whole number (used for long numbers)           64 bits
 short     a whole number (used for short numbers)          16 bits
      Example:
      char aCharacter;
      int aNumber;
      You can assign a value to a variable at the same time that it is declared. This process
      is known as initialization:
      char aCharacter = 'a';
      int aNumber = 10;
Q5 Declaring a variable and then giving it a value
      char aCharacter; aCharacter = 'a'; int aNumber; aNumber = 10;
      NOTE: A variable must be declared with a data type or an error will be generated!
      The data type of a variable should be used only once with the variable name - during
      declaration. After that, you can refer to the variable by its name without the data type.
      Naming variables
      Rules that must be followed when naming variables or errors will be generated and
      your program will not work:
      •      No spaces in variable names
    •       No special symbols in variable names such as !@#%^&*
    •       Variable names can only contain letters, numbers, and the
    underscore ( _ ) symbol
    •       Variable names cannot start with numbers, only letters or the
    underscore ( _ ) symbol (but variable names can contain numbers)
    Recommended practices (make working with variables easier and help clear up
    ambiguity in code):
    •       Make sure that the variable name is descriptive of what it stores - For example,
    if you have a variable which stores a value specifying the amount of chairs in a room,
    name it "numChairs".
    •       Make sure the variable name is of appropriate length - Should be
    long enough to be descriptive, but not too long. Also keep in mind:
Q6 OPERATORS IN JAVA
           Arithmetic operator
           Unary Operator
           Comparison Operator
           Short-Circuit Logical operator
           Bitwise Operator
           Shift Operator
           Ternary operator
           Assignment operator
(1)Arithmetic operator
The Java programming language provides operators that perform addition, subtraction,
multiplication, and division. There's a good chance you'll recognize them by their
counterparts in basic
mathematics. The only symbol that might look new to you is "%", which
divides one operand by another and returns the remainder as its result.
+       additive operator (also used for String concatenation)
-       subtraction operator
*       multiplication operator
/      division operator
%       remainder operator
The following program, ArithmeticDemo, tests the arithmetic
operators.
class ArithmeticDemo {
public static void main (String[] args){
int result = 1 + 2; // result is now 3
System.out.println(result);
result = result - 1; // result is now 2
System.out.println(result);
result = result * 2; // result is now 4
System.out.println(result);
result = result / 2; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10 result = result % 7; // result is now 3
System.out.println(result);
(2)Unary Operator
There are five types of Unary Operators.
(1)The Increment or Decrement operator:++ --
(2)the unary plus and unary minus:+ -
(3)the bitwise inversion operator:~
(4)the Boolean complement operator:!
(5)the cast operator: ()
(1)The Increment or Decrement operator:-
The increment/decrement operators can be a prefix or a postfix .In a prefix expression (++ x
or -- x), an operator is applied before an operand while in a postfix expression (x ++ or x --)
an operator is applied after an operand. In both conditions 1 is added to the value of the
variable and the result isstored back to the variable. However both operators have the same
effect as "x = x + 1;"
Although there is a major difference between a prefix and
a postfix expressions. In a prefixexpression, a value is incremented first
then this new value is restored back to the variable. On the other hand,
In postfix expression the current value is assigned to a variable then it is incremented by1 and
restored back to the original variable.
(2)unary plus and minus operator
Unary Plus (+) Operator
Unary plus operator (+) indicates positive value. This (+) operator is used to perform a type
conversion operation on an operand. The type of the operand must be an arithmetic data type
i.e. if a value of the integer operand is negative then that value can be produced as a positively
applying unary plus (+) operator. For example, lets see the expressions shown as:
int x = 0;
int y = (-
25);
x = (+y);
In this expression, a negative value is assigned to the variable "y". After applying unary plus
(+)operator on the operand "y", the value
becomes 25 which indicates it as a positive value.
However a number is positive without using unary plus (+) operator, if
we have initially assigned it positively into the operand in the program.
II. Unary minus (-) Operator
Unary minus operator (-) indicates negative value and differ from the unary plus operator.
This (-) operator is also used to perform a type conversion operation on an operand. If a value
of the integer operand is positive then that value can be produced as a negatively applying
unary minus (-) operator. For example, lets see the expressions shown as:
int x = 0; int y = 25; x = (-y);
In this expression, a positive value is assigned tothe variable "y". After applying minus plus
(-)operator on the operand "y", the value becomes "-25" which indicates it as a negative value.
This behavior represents the number in two's complement format.
(3) The Bitwise Inversion operator
The bitwise NOT "~" operator inverts each bit in the operand i.e. this operator changes all
the ones to zeros and all the zeros to ones. Remember that this operator takes only one operand
or parameter. Hence in the program code given below only one parameter has been taken.
(4)The Boolean Complement Operator
Logical Compliment (!) Operator
The logical compliment (!) operator is also known as Boolean Negation Operator. It is used
to invertthe value of a boolean type operand i.e. the type of the operand must be boolean while
using this operator,. If the value of the boolean operand is false, the ! operator returns true.
But, if the value of the operand is true, the ! operator returns false.
For example, lets see the statements shown as:
boolean result = (2>1); result = !result System.out.println("2 is geater than 1: " + result);
In these statements, the first expression returns true to the
variable "result" but at the end of the program, the output is shown as false because the
compliment (!) operator inverts the value of the variable "result".
Lets have one more example using unary operators in different flavors:
(3) Comparision Operator
All the standard comparison operators work for primitive values (int, double, char, ...). The
== and != operators can be used to compare object references, but see Comparing Objects for
how to compare object values
The result of every comparison is boolean (true or false).
operator meaning
<         less than
<=        less than or equal to
==        equal to
>=        greater than or equal to
>         greater than
!=        not equal
(4)Short-circuit operator
Java provides two interesting Boolean operators not found in most other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are known as short-
circuit logical operators. As you can see from the preceding table, the OR operator results in
true when A is true, no matter what B is. Similarly, the AND operator results in false when A
is false, no matter what B is. If operator results in false when A is false, no matter what B is.
If you use the | | and && forms, rather than the | and & forms of these operators, java will not
bother to evaluate the right-hand operand alone. This is very useful when the right-hand
operand depends on the left one being true or false in order to function properly. For example,
the following code fragment shows
how you can take advantage of short-circuit logical evaluation to be sure that a division
operation will be valid before evaluating it:
if ( denom != 0 && num / denom >10)
Since the short-circuit form of AND (&&) is used, there is no risk of causing a run-time
exception when denom is zero. If this line of code were written using the single & version of
AND, both sides would have to be evaluated, causing a run-time exception when denom is
zero.
It is standard practice to use the short-circuit forms of AND and OR in cases involving
Boolean logic, leaving the single-character versions exclusively for bitwise operations.
However, there are exceptions to this rule. For example, consider the following statement:
if ( c==1 & e++ < 100 ) d = 100;
Here, using a single & ensures that the increment operation will be applied to e whether c is
equal to 1 or not.
(5)Bitwise Operator
Java's bitwise operators operate on individual bits of integer (int and long) values. If an
operand is shorter than an int, it is promoted to int before doing the operations.
It helps to know how integers are represented in binary. For example the decimal number 3
is represented as 11 in binary and the decimal number 5 is represented as 101 in binary.
Negative integers are store
in two's complement form. For example, -4 is 1111 1111 1111 1111
1111 1111 1111 1100.
Operator          Name Example           Result Description
a & b and         3&5 1          1 if both bits are 1.
a|b     or        3|5     7      1 if either bit is 1.
a^b     xor       3^5     6      1 if both bits are different.
~a      not       ~3      -4     Inverts the bits.
  <<         Signed left shift
  >>      Signed right shift
  >>>     Unsigned right shift
  Java provides two right side shifting operator (>> >>>) and one left shift operator(<<).A
  Shift operator allow us to perform bit manipulating on data.This table summarize the
  shift operator in java programming language.
  Operator                           Use                                operation
  >>                                 a>>b                               Shift bits a right by
                                                                        distance b
  <<                                 a<<b                               0101(5)
                                                                        Shift bits>>
                                                                                   of 1a 0010(2)
                                                                                         left by
                                                                        distance b
                                                                        0101(5)<< 1 1010(10)
  >>>                                a>>>b                              Shift bits of a by
                                                                        distance b
                                                                        0101(5)>>> 1 0010(2)
(7)Ternary Operator
Interested in saying a lot while writing a little? In a single line of code, the Java
ternaryoperator let's you assign a value to a variable based on
a boolean value (either a boolean field, or a statement that evaluates to
a boolean result).
At its most basic, the ternary operator (also known as the conditional operator) can be used
as an alternative to the Java if/then/else syntax, but it actually goes beyond that, and can even
be used on the right hand side of Java statements.
Simple ternary operator examples
Although it may be a little confusing when you first see it, the ternary operator lets you make
powerful decisions with a minimal amount of coding.
One use of the Java ternary operator (also called the conditional operator) is to assign the
minimum (or maximum) value of two variables to a third variable, essentially replacing
a Math.min(a,b) or Math.max(a,b) method call. Here's an example that
assigns the minimum of two variables, a and b, to a third variable
named minVal is:
minVal = (a < b) ? a : b;
In this code, if the variable a is less than b, minVal is assigned the value of a; otherwise,
minVal is assigned the value of b. Note that the
parentheses in this example are optional, so you can write that same statement like this:
minVal = a < b ? a : b;
I think the parentheses make the code a little easier to read, but again, they're completely
optional.
You can take a similar approach to get the absolute value of a number, using code like this:
int absValue = (a < 0) ? -a : a;
(8)Assignment operator
Assignment operator is the most common operator almost used with all programming
languages. It is represented by "=" symbol in Java which is used to assign a value to a variable
lying to the left side of the assignment operator. But, If the value already exists in that variable
then it will be overwritten by the assignment operator (=). This operator can also be used to
assign the references to the
Unit 2
Q1 Explain IF ,Else and Else IF with Example
The if statement
The if statement will execute some code if a condition is true.
Syntax:
if(condition)
Example:
Perform this action;
          int aNumber = 5; //check if aNumber equals 5 and if it is print a
          message if (aNumber == 5)
                   System.out.print("aNumber is equal to 5");
          =====================================================
          Output:
          aNumber is equal to 5
The else statement
The if statement executes some code if a condition is true, but what if the condition is false?
The else statement will execute some code if the condition in the if statement is false.
Syntax:
if(condition)
else
perform this action;
perform this action if the above condition is false;
          int aNumber = 10; //check if aNumber equals 5 and if it is print a message if
          (aNumber == 5)
                  System.out.print("aNumber is equal to 5");
          }
           //otherwise print a different
          message else{
                   System.out.println("aNumber equals a number other than 5");
          =================================================
          ====== Output:
          aNumber equals a number other than 5
The else-if statement
Any condition can be only true or false, but what if you needed to test a variable for more
than one value? This is where the else-if statement comes in. The else-if statement performs
an action if the variable in the if statement is another value specified in the else- if statement
itself.
Syntax:
if(condition1)
          perform this action;
else if(Condition2)
          perform this action;
}
 Example:
        int aNumber = 7;
        if (aNumber == 5)
                System.out.print("aNumber is equal to 5");
         else if (aNumber == 7)
                System.out.print("aNumber is equal to 7");
        =====================================================
        ====== Output:
        aNumber is equal to 7
Q2 Explain switch statement with example
The switch statement is specifically designed for comparing one variable to a number of
possible values. It can be thought of as a substitute for the if, else-if, else structure. There is
an important keyword used within the switch structure, and that keyword is the break
keyword. The break keyword is used to make sure that the switch structure will not fall
through to the next possible value.
Syntax:
switch(variable)
case possible value:
perform this action;
break;
case possible value:
perform this action;
break;
case possible value:
perform this action;
break;
default:
perform this action if none of the values match;
Example:
Example:
int aNumber = 7;
switch(aNumber)
{
//test if aNumber equals one of a set of values and if it is print a message
case 1: case 2: case 3:
System.out.print("aNumber is equal to 1");
break;
System.out.print("aNumber is equal to 2");
break;
System.out.print("aNumber is equal to 3");
break;
case 7: System.out.print("aNumber is equal to 7");
break;
//test if aNumber equals an unspecified value and if it is print a message default:
System.out.print("aNumber is not equal to any of the values specified");
=================================================================
== Output:
aNumber is equal to 7
Q3 Explain For loop ,While , and do-while loop
The for loop
The for loop is used to repeat a task a set number of times. It has three parts.
•      variable declaration - Initializes the variable at the beginning of the loop to some
value. This value is the starting point of the loop.
•      condition - Decides whether the loop will continue running or not.
While this condition is true, the loop will continue running. Once the condition becomes false,
the loop will stop running.
•      Increment/decrement statement - The part of the loop that changes the value of the
variable created in the variable
declaration part of the loop. The increment/decrement statement is the part of the loop which
will eventually stop the loop from running.
Syntax:
for(int a_variable = initial_value ; a_variable < end_value ;
a_variable_increment/decrement)
code to be executed;
Example:
for(int a = 1; a < 11; a++)
System.out.print(a + " ");
================================= Output:
1 2 3 4 5 6 7 8 9 10
Lets take apart the loop from the above example to see what each part does.
•      int a = 1 - A variable named a is declared with the value of 1.
•      a < 11 - The condition of the loop, states that as long as the
variable a is less than 11, the loop should keep running.
•       a++ - The increment statement part of the loop, states that for every iteration of the
loop, the value of the variable a should increase by 1. Recall that initially a is 1.
•      System.out.print(a + " ") - Print the value of a together with a
single space for each time the loop runs.
The above loop will execute the code between the braces 10 times because a begins at 1 and
ends at 10. This counter is what runs the loop.
The while loop
The while loop works differently than the for loop. The for loop repeats a segment of code a
specific number of times, while the while loop repeats a segment of code an unknown number
of times. The code within a while loop will execute while the specified condition is true.
Syntax:
Initialization;
while(condition is true)
execute this code;
increment/decrement // not compulsory
Example:
int num = 0;
while(num < 25)
num = num + 5; System.out.print(num + " ");
================================================ Output:
5 10 15 20 25
In the above code, a variable named num is initialized with the value of
0. The condition for the while loop is that while num is less than 25, 5 should be added to
num and it should be printed (together with a single space). Once the value of num is greater
than 25, the loop will stop executing.
The do-while loop
The do-while loop is very similar to the while loop, but it does things in reverse order. The
while loop - while a condition is true, perform a certain action, the do-while loop - perform a
certain action while a condition is true. Also, the code within a do-while loop will always
execute at least once, even if the specified condition is false. This is because the code is
executed before the condition is tested.
Syntax:
do
execute this code;
} while (condition);
Example:
int num = 5;
do{
num = num + 2; System.out.print(num + " ");
} while (num < 25);
=================================================== Output:
7 9 11 13 15 17 19 21 23 25
In the above code, a variable named num is initialized with the value of
5. The condition for the do-while loop is that 2 should be added to num
and it should be printed (together with a single space) while num is less than 25. Once the
value of num is greater than 25, the loop will stop executing.
Q4 Explain break and continue.
You can completely break out of a loop when it is still running. This is achieved with the
break keyword. Once a loop is exited, the first statement right after it will be executed. The
break keyword provides an easy way to exit a loop if an error occurs, or if you found what
you were looking for.
Example:
for(int a = 1; a < 10; a++){ System.out.print(a + " "); if(a == 5) {break;} }
System.out.print("You have exited the loop");
In the above example, the for loop is set to iterate 9 times and print the current value of the
variable a during each iteration. The if statement within the loop states that when the variable
a is equal to 5, break out of the loop.
Output:
1 2 3 4 5 You have exited the loop
Continuing a loop
While you can break out of a loop completely with the break keyword, there is another
keyword used when working with loops - the continue keyword. Using the continue keyword
in a loop will stop the loop at some point and continue with the next iteration of the loop from
the beginning of it.
Example:
for(int a = 1; a < 10; a++){ if(a == 5){continue;} System.out.print(a + " ");
In the above example, the for loop is set to iterate 9 times and print the current value of the
variable a during each iteration. The if statement within the loop states that when the variable
a is equal to 5, stop the loop and continue with the next iteration of the loop from the
beginning of it. For this reason, all the numbers except the number 5 are printed.
Output:
12346789
NOTE: For the continue keyword to work properly, the conditional statement needs to come
first just like in the above example