Organized Merged
Organized Merged
1. Introduction to Java
2. Input Statement
3. Conditional Statement
4. Tokens
5. Datatypes
6. Expressions
7. Class Math
8. Iteration - Counters
9. Iterations – Accumulator
10.Nested Loops
11. Modulus
                                CHAPTER 1
                       INTRODUCTION TO JAVA
Java is Third Generation Object Oriented Programming Language developed
by Sun MicroSystems in the year 1991. It was originally named as Oak. It is
designed to be small, simple and portable across different platforms. Java is
both a programming language and a platform. It is programming language,
because you can create various types of applications. It is also a platform for
application development. Platform refers to combination of hardware and
system software.
Characteristics of Java
1.Write Once Run Anywhere(WORA) :compiled Java program can be run
anywhere without making any changes.
2. Light Weight Code :Because of advanced Java API(application program
interface) even complex applications can be developed with light code.(API
consists of pre-compiled library files)
3. Security : This feature make Java programs safe for the platform independent
on which they execute
4. Built-in graphics : This features makes development of visual application
very simple
5. Object-Oriented Language: Being an object oriented language, java can be
used to simulate real world objects.
6.Supports Multimedia : Ideally suited for integration of video, audio and
animation in stand-alone and internet based applications
7.Open product :Being an open product, it can be down-loaded and freely
available for all.
Java Compilation Process
To understand Java compilation process you need to understand the
development of computer languages Generation Computer
Languages
Machine Level            Assembly Level Language /           High Level
Language/ First          Second Generation Computer          Language
Generation               Language
Computer
Language/ Binary
Language
Computer can             Assembly language uses binary       These languages
understand only one      number with Mnemonics. These        are similar to
language called          Mnemonics are 3 letter words like English language
Binary Language          ADD, SUB, MUL, DIV which            and a common
which is made of 0’s     were used instead of codes. As      person could
and 1’s. O or 1 is       computer can understand only        easily understand
called a bit (Binary     binary language, there is a         and program it. It
                                       1
digit). This binary      translator which converts             has many English
language was difficult   Mnemonics to Machine level            words like if,
to understand and to     language. This translator is called   while, then, for
code it. The user had    Assembler.                            etc.
to know the working      Some of the draw backs of
of the computer. The     Machine level language still
user had to memorize     existed here like:
the codes which               the user need not memorize
varied from machine             the code but they had to
to machine. So this             know the internal working
was not popular.                of the computer.
                              The user had to know
                                binary language.
               Compiler                                    Interpreter
1. Translates High Level Language to        1. Translates High Level Language to
Machine Level language all at once.         Machine line by line.
2. It is Fast.                              2. It is slow.
3.. HLL like C, COBOL, FORTRAN              3. HLL BASIC uses Interpreter.
and Pascal uses Compiler
                                        2
Java Compilation Process
 Java uses both compiler(jdk) and interpreter(JVM) to translate Source code to
Machine code.
   1. First Java uses compiler(jdk) to translate high level language (source
       code) to Byte code. This byte code is independent of the computer
       system it has been compiled.
   2. Secondly, Java uses an interpreter (called JVM) which reads the byte
       code line by line and converts it to machine code (native executable
       code) depending on the platform or computer on which the application or
       program is to executed.
                                         3
Java Applets                             Java Application
    A small program.                        A large program.
    Created by extending the                Created by writing the program
      java.applets.Applets                    inside the main method.
    They are executed on web                They are executed using java
     browser.                                 compiler jdk.
BlueJ
BlueJ is a window based IDE(Integrated Development Environment), for JDK
(Java Development Kit) which includes an editor, a debugger and a viewer. It
offers an easy way to run java program and view the documents.
There are many more java IDE’s, which includes an editor, a debugger and a
viewer. Some of them are JCreator, NetBeans, Ecllipse, etc. All the IDE’s use
the same java jdk compiler. As the compiler is same the java language and the
syntax remains the same so, we can use any IDE to type the program and get the
result.
The first 128 characters in UNICODE character set and ASCII character set are
identical. i.e. They represent the same characters.
Assignment
1.Give one word for the following:
   a) The original name for Java.
   b) The program which can run anywhere without making changes
   c) The software that can be downloaded
   d) The language used to simulate real world objects.
   e) Set of instruction
   f) The program written by the programmer
                                      4
   g) The process of converting the source program to machine language
   h) The code which is independent of the machine that it has to run upon.
   i) It is implemented on top of existing processors and hides the OS from
       Java application.
   j) They are pre-compiled library code that can be used in your programs.
   k) It needs a web browser to execute the program.
   l) It can run independently on any platform using jdk compiler and JVM.
2.Give the full form:
i)WORA ii) IDE        iii) UNICODE iv) ASCII        v)JVM             iv)API
3.Differentiate the following:
   i)     UNICODE & ASCII code
   ii)    Bytecode & Native executable code
   iii) Jdk & JVM
   iv) Compiler & Interpreter
   v)     Internet applets & Stand alone application
4.Answer the following:
   i)     How is java compilation process different from the ordinary
          compilation process?
   ii)    What is byte code and JVM?
   iii) What are the 2 types of Java program?
                                      5
                                         CHAPTER 2
                                  INPUT - OUTPUT STREAMS
   Stream : A stream in java is a sequence of data. There are two kinds of Streams −
        InputStream − The InputStream is used to read data from a source. Data comes
         from the keyboard to the program.
        OutputStream − The OutputStream is used for writing data to a destination.
         From the computer to the monitor.
   Java provides the following three standard streams −
        Standard Input − This is used to feed the data to user's program and usually a
         keyboard is used as standard input stream and represented as System.in.
        Standard Output − This is used to output the data produced by the user's
         program and usually a computer screen is used for standard output stream and
         represented as System.out.
        Standard Error − This is used to output the error data produced by the user's
         program and usually a computer screen is used for standard error stream and
         represented as System.err.
   Package: It is a group of related classes and interfaces. Its main advantage is that, it
   provides a convenient mechanism for managing a voluminous set of classes and
   interfaces and avoiding name conflicts. One can also create their own package.
   import : is a statement to include a package in the program.
   Statement
     A statement is a single line of instruction which is terminated by a semicolon.
   To accept values using class Scanner
   We can input to the program from the keyboard through the methods of the class
   Scanner. To include the package of the class Scanner in a program we use import
   statement.
    import java.util.Scanner;
   import java.util.Scanner;
     Or
   import java.util.*;
   The former statement gives access only to the class Scanner present in the package
   java.util.
                                               5
The latter statement gives access to all the classes present in the package java.util.
Once the package is imported to the class then an object of the class is created to take the
control of the methods present in it. System.in is connected to the keyboard. It is passed
as parameter to Scanner class to create an object for the class Scanner.
       Scanner sc = new Scanner(System.in);
    int a = sc.nextInt()
                   next()                                              nextLine()
This is method of class scanner which                 This is a method of class scanner which
accepts a word from the keyboard                      accepts a String from the keyboard.
                  print()                                               println()
This methods prints the value and then the            This method prints the value and moves the
cursor remains on the same line. So,                  cursor to the next line. So, println()
print() does not adds new line                        automatically adds new line
character(\n) at the end of the text being            character(\n) at the end of the text being
printed.                                              printed.
                                                  6
Comments
Comments are text notes or documents added by the programmer to explain the source
code or program. These comments are ignored by the compiler. There are two types of
comments in java. They are:
     Single Line comments
     Multiple Line Comments
           Single line Comment                      Multiple line Comment
The comment can be given in a Single      The comments can be given in Multiple
Line.                                     lines.
Eg:                                       Eg:
// This program adds 2 numbers            /* This is a very trick program which need
                                          to be figured out with lot of effort */
Write a program to accept two integers and find their sum. Print the result in the
following format: Sum of -------- and -------- is -----------
import java.util.Scanner;
class Addition
 { public static void main(String args[])
    {Scanner Sc= new Scanner(System.in);
      int n1,n2,sum;
     System.out.println("Enter first number");
     n1=Sc.nextInt();
     System.out.println("Enter second number");
     n2=Sc.nextInt();
     sum=n1+n2;
    System.out.println("Sum of "+ n1 +” and “+n2 +” is “+ sum);
}}
Write a program to accept roll number, name, Marks in English, Math and
computer. Find their total and average and print the result in a neat format- using
Scanner class
import java.util.Scanner;
class Student
 { public static void main(String args[])
    {Scanner Sc= new Scanner(System.in);
     String n;
     int rn;
     double eng,math,comp,t,av;
     System.out.println("Enter your name");
     n=Sc.nextLine();
                                         7
   System.out.println("Enter your rollnumber");
   rn=Sc.nextInt();
   System.out.println("Enter your marks in English");
  eng=Sc.nextDouble();
  System.out.println("Enter your marks in Maths");
  math=Sc.nextDouble();
  System.out.println("Enter your marks in Computer");
  comp=Sc.nextDouble();
  t=eng+math+comp;
  av=t/3;
  System.out.println("-----------------------------------");
  System.out.println("        Marks Card");
  System.out.println("------------------------------------");
White Space: They are spaces bar, tabs and new lines for improving visual appearance
of the source code.
Escape sequence : Even escape sequence are used with output to improve visual
appearance.
Some of the escape sequence are: \n \t \\ \” \’
Exercise 2.1
Write a java statement to print the following:
a) This is the time for all the Good men in the world.
b) “It’s fine to celebrate success, but it is more important to heed to the lessons
of failure.” – Bill Gates.
c) To win big, you
    sometimes have to take big risks. (use one print statement)
d) The only limit to the height of your achievement is –
      the reach of your dreams and your willingness to work hard for them.
            (use one print statement)
e) Todays date is 24\10\2000
                                               8
Exercise 2.2
Write the output of the following statement
 a)     System.out.print("Writing program");
        System.out.print(" is fun... \n Writing Java program is even more fun");
b) Write a program to accept Length and breadth and calculate area of Rectangle. Print
all in the following format: Length is --------- breadth is ------------ Area is -------------
c) Write a program to accept radius and calculate area of circle and its circumference.
Print the result in the following format:
     Radius is -----------
     Area is -----------=
     Circumference is -------------
   d)Write a program to accept 3 integer values (two sides and the height) and calculate
       the area of trapezium using formula:
                      1
               area= height (a  b)
                      2
  e) Write a program to accept employee number, Name and basic salary. Calculate
House Rent Allowance which is 14.5% of the annual salary. Print the result in the
following format:
    Employee Number -------- Name -------------
    Basic Salary ------------------ House Rent allowances --------------
****************************************************************
                                               9
                                         CHAPTER 3
                                     Programming constructs
In a program, statements may be executed sequentially, selectively or iteratively. Every
programming language provides constructs to support sequence, selection or iteration.
Sequence: In sequence construct the statements are executed one after the other in a
sequence. In java, program starts with the first statement of the main () and ends with the last
statement of the main.
Selection: In selection construct, execution of the statement(s) depends upon a condition-
test. If the condition evaluates true then the statements following the condition is evaluated.
Iteration: The iteration construct means repetition of set of statements depending on a
condition test. As long as the condition is satisfied the set of statements are executed. It is
also called as looping statements. The set of statements that are repeated again and again are
called the body of the loop. The condition on which the execution or exit of the loop depends
is called the exit condition or test condition.
Relational operator
The following are the relational operators which are used in condition to compare the values.
               Relational    Name
               operator
               >             Greater than
               <             Lesser than
               >=            Greater than equal to
               <=            Lesser than equal to
               ==            Equal to
               !=            Not equal to
                                               11
Logical operator
When 2 or more conditions i.e compound condition are to be given then a (connective)
logical operator is used to connect them. The 3 logical operators are:
               Logical       Name
               Operator
                 !           NOT
                  &&         AND
                   ||        OR
                                              12
(true) || ! (false) && (false)   It will execute the condition
(true) || (true) && (false)      It will execute the !(NOT) according to hierarchy
(true) || (false)                It will execute && (AND) according to hierarchy
(true)                              It will execute || (OR) according to operator
precedency
   1. Write a program to Create a class named “Student” to accept Roll number, name,
      marks in English, maths and computers. Calculate total and average. Find the result
      based on the condition:
                                   Result
       Average
       >=80                         “Distinction”
       >=60 and <80                 “First Class”
       >=40 and <60                 “II Class”
       Else                         “Fail”
       Print the result in the following format:
              Roll number is -------- name is ------
             Marks in English is ----- Maths is ----- Computers is -----
             Total is ---- average is -----
             Result is -------
                                               13
2. Write a program to create a class named “Electricity” to accept meter numbers, Name of
   the consumer, Previous meter reading and the present meter reading. Calculate units
   consumed and cost based
   on the following condition:
   3. A telephone department wishes to compute telephone bills for the customers using the
      following rules: minimum Rs. 250 for the first 50 units plus Rs. 1.20 per unit for the
      next 200 units, plus Rs.1.10 for the next 150 units and Rs 1.00 for every unit above
      that. Write a java code to take the following as input: customer number and number of
      units. The output should contain : customer number, Number of units and amount of
      bill.
   4. Define a class name Employee ( int) pan to store personal account number, ( String)
      name to store name, (double) taxincome to store annual taxable income. Calculate tax
      based on the condition:
      Total Annual Income                 Tax Rate
      Upto Rs.1,00,000                    No Tax
       From 1,00,000 to 1,50,000          10% of income exceeding Rs.1,00,000
       From 1,50,000 to 2,00,000          Rs. 5000 + 20% of income exceeding Rs 1,50,000
      Above 2,00,000                      Rs. 25000 + 30% of the income exceeding Rs.
                                          2,00,000
      Print the result in the following format:
                                                 14
        Pan number        Name           TaxIncome Tax
            ----- ----             -----        --
   5. Accept the distance traveled by the passenger and calculate the cost based on the
      conditions:
                   Distance                       Cost/km
                    10km                                Rs. 10
                       next 20kms                       Rs. 6
                        next 30kms                        Rs. 4
        Calculate cost and print it.
Control variable : The variable passed as an argument to the switch statement that decides
which statements is to be executed is known as a control variable.
break statement: The statement used at the end of each case which acts as the case
terminator. As soon as the break is encountered the control is forced to move out of the
switch block.
default case: If no case is matched in the switch block for a given values of the control
variable, default case is executed implicitly.
System.exit(0): exit() is a method in the class System, in the package java.lang. This method
terminates the running program by terminating JVM.
exit(0) : Generally used to indicate successful termination.
exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful
termination.
                                               15
Note : A case statement cannot exit by itself so a break statement is used.
Syntax
        switch( integer/char)
           {
              case constant1 :
                    …..
                   break;
               case constant2:
                   …….
                   break;
               case constant3:
                     ……..
                    break;
                default:
                      ……..
       }
Characteristics of switch
  1. A switch statement can only work on == relational operator.
  2. Switch statements works only with integer, character and String data types.
  3. No two case labels in the same switch can have identical values. If we compile the
      program which has a switch statement containing two cases with identical values then
      the compiler will flash a syntax error message “duplicate case label”.
  4. When a value of a variable or an expression is to be compared with the list of possible
      integer or character or String constants switch is preferred over nested if. As it faster
      than nested-if.
                 Switch                                            If-else
   The switch statement test only for             It can work on all the relational
      equality                                       operations
   It works on int(byte, short, int, long)           if works on all the datatypes
      datatype, char datatype and String
      datatype.                                    If can handle a range of values along
                                                     with logical OR (||)
   The switch statement selects its
      branches by testing the value of the
      expression with the one in the case          Nested if is not efficient
      constant. It can handle a range of
                                              16
      values
                default:
                   System.out.println("Wrong Entry......");
               }}}
Write the equivalent switch case for the following if- else if
{ if(a==2 || a==4 || a==6 || a==8)               switch(a)
      System.out.println(" Even Digit");             {case 2 : case 4: case 6: case 8:
 else if(a==1 || a==3 || a==5 || a==7 || a==9)           System.out.println(" Even Digit");
      System.out.println(" Odd Digit");                  break;
     else                                             case 1: case 3:case 5: case 7: case 9:
       System.out.println("Zero");                      System.out.println(" Odd Digit");
   }                                                    break;
                                                      default:
                                                        System.out.println(" Zero");
                                                    }
                                    Switch statement
   1. Write a program to accept day of the week as number and print it in words
   2. Write a program to accept month as number and print the maximum number of day in
      the given month
   3. Write a program to accept an alphabet and print if it a vowel or a consonant
                                              18
                          Ternary operator (conditional operator)
    The ternary operator ?: can replace if-else statement. They work on 3 operands and so the
name ternary operators. They are more concise compared to if statement. But when it comes
to nested if they become more complex.
    Syntax:
          (Condition)? Expression1:expression2
Expression1 is evaluated, if the condition results in true else Expression3 is executed
     eg. int c = (a>b) ? a : b
Comparing if and ?:
     Ternary operator is more concise and compact
     Only single values can be assigned or evaluated. Whereas in if multiple statements
       can be assigned or evaluated.
      Ternary ( >: ) Operator                          if-else statement
1. Ternary operator can give only one     1.If statement is flexible and can have
value                                     more than one statement in a block.
ii. This operator is more concise, clean  ii. if in its nested form is also not so
and compact but in its nested form it is  complex.
more complex.
Question 1
   Create a class named Shop which offers discount on the purchase made based on the
following condition:
         Purchase Amount         Discount
            <=5,000                10% on the purchase amount
            >5,000 & <=12,000      12% on the purchase amount
         >12,000                   18% on the purchase amount
Write a program to accept Bill number(bno), Name (n), Amount purchase (ap). The
program should calculate the discount based on the amount purchased and and also
calculate amount paid and print the result in the given format:
     Bill Number        Name           Purchased amount         Discount Amount paid
           --------         ----                  ---------        ----   ---
Question 2
Define a class taximeter to accept int taxino – to store taxi number String name – to store
passenger’s name
    int km – to store number of kilometer travelled
 Calculate bill for a customer according to given conditions
        Kilometers travelled(km)        Rate/km
        ≤1 km                           Rs.2
        >1 km ≤ 6                 Rs. 5
        >6 km ≤ 12                Rs. 7
        >12 km ≤ 18               Rs.9
        >18 km                    Rs. 10
 Display the details in the following format:
     Taxino Name Kilometers travelled         Bill amount
      -           -                -                     -
Question 3
Define a class to accept employee number, name and their basic salary. Calculate bonus
based on the following condition:
Question 6
   Create a class named Shop which offers discount on the purchase made based on the
following condition:
         Purchase Amount         Discount
            <=5,000                10%
            >5,000 & <=12,000    Previous discount + 6% on the amount
                                 >5,000
         >12,000                 Previous discounts + 8% on the amount
                                 >12,000
Write a program to accept Bill number(bno), Name (n), Amount purchase (ap). The
program should calculate the discount based on the amount purchased and print the result in
the given format:
       Bill Number       Name               Purchased amount         Discount
           --------         ----               ---------                ----
Question 7
       Write a menu driven program with the following options:
        1. Area of Rectangle
        2. Area of Circle
        3. Perimeter of a Square
                                             23
                WORKSHEETS ON CONDITIONAL STATEMENT AND ITERATION
Question 1
Write a program to accept roll number, name, class, section, marks in English, Math
and Computers. Find the total and average. Based on the average print the result
according to the given table.
         Average                Result
         >=80                   “Distinction”
         >=60                   “I class”
         >=40                   “II Class”
         Else                   “Fail”
Question 2
  Create a class named Shop which offers discount on the purchase made based on
the following condition:
         Purchase Amount        Discount
           <=5,000                10% on the purchase amount
           >5,000 & <=12,000      12% on the purchase amount
         >12,000                  18% on the purchase amount
Write a program to accept Bill number(bno), Name (n), Amount purchase (ap). The
program should calculate the discount based on the amount purchased and and also
calculate amount paid and print the result in the given format:
        Bill Number Name                          Purchased amount                 Discount Amount paid
            --------              ----                   ---------                       ----                 ----
-------------------------------------------------------------------------------------------------------------
Question 3
Write a program to generate a random number between 1 to 100 using the built-in
Math function. Give the user 10 chances to guess the number. If the number guessed
by the user is greater than the number the computer has generated then print the
message “Think of a smaller number”. If the number guessed by the user is lesser than
the number the computer has generated then print the message “ Think of a bigger
number”. If the number the computer has generated is same as the on guessed by the
user then print the message that “you have guessed the correct number” and print
the number of chances they have taken to guess the number and exit the program. If
                                                        30
the user fails to guess the number if 10 chances then print the number generated by
the computer and exit the program.
-------------------------------------------------------------------------------------------------------------
Question 4
Write a program to generate a quiz. Choose any 5 questions with four choices. Display
each question with the choice(1/2/3/4). Accept the answer ( ie. Choice). If the answer
is correct add 5 marks to each question. At the end print the total score.
Question 5
Write a menu driven program depending on the user’s choice for the following:
 1. Area of square
 2. Area of rectangle
 3. Area of Triangle
If the user enters a wrong choice print the message “Wrong choice”
---------------------------------------------------------------------------------------------------------------
Question 6
Write a menu driven program to accept principal(p), time (t) and rate(r) and calculate
simple interest.
----------------------------------------------------------------------------------------------------------------
Question 7
 There are different 100 coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour as char data type (R-Red G-Green B-Blue W-White) and
do the job of sorting the beads and print the number of beads of each colour.
----------------------------------------------------------------------------------------------------------------
                                                        31
Question 8
  There are different n coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour as char data type (R-Red G-Green B-Blue W-White) and do
the job of sorting the beads and print the number of beads of each colour.
----------------------------------------------------------------------------------------------------------
Question 9
  There are different coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour a colour as char datatype (R-Red G-Green B-Blue W-
White) and do the job of sorting the beads and print the number of beads of each
colour.
---------------------------------------------------------------------------------------------------------
Question 10
  There are different coloured beads in a box - Red, Green, Blue and white. Write a
program to accept a colour as char datatype (R-Red G-Green B-Blue W-White) and do
the job of sorting the beads and print the number of beads of each colour. The
program should stop when the last colour entered is ‘0’.
                                                     32
                             CHAPTER 6
                        CHARACTER SET OF JAVA
       The character set used in java is Unicode character set. This Unicode is a 16-bit
character coding system and currently supports more than 34,000 defined characters derived
from 24 languages all over the world. The first 128 characters in Unicode character set are
identical to ASCII character set.
                                TOKENS OF JAVA
Tokens are the smallest elements/unit of the Java Program. There are 5 types of
tokens. They are
   1. Reserved words
   2. Identifiers
   3. Literals
   4. Separators
   5. Operators
1.Reserved WordsReserved words are also called Keywords. They have specific meaning
in Java and cannot be used as names for variables, classes, and methods. All keywords
                                            37
are written in lower case letters. Since java is case sensitive, one can use these words as
identifiers by changing one or more letters to upper case.
2.Identifiers
          They are programmer-defined tokens. They are names of the classes,
methods, variables, objects in a program.
Java identifiers follow the following rules:
    They should begin with an alphabet, or an underscore or dollar sign characters.
    They can be followed by an alphabet or underscore or a digit.
    Uppercase and lowercase letters are distinct
    They can be of any length
    They must not be a boolean literal( true/ false) , keyword, or null literal.
   Note : Identifiers must be meaningful, short enough to be quickly and easily typed and
   long enough to be descriptive and easily read. Java developers have some naming
   conventions.
    Names of all public methods and instance variables start with a leading lowercase
       letter.
     eg. total
    When more than one word is used in a name, the second and subsequent words are
       marked with a leading uppercase letters.
     eg. simpleInterest
    All private and local variables use only lowercase letters combined with underscores.
      eg. sales_commission
    All classes start with a leading upper case letter
      eg. Student
    Variables that represent constant values use all uppercase letters and underscores
       between words.
      eg. MAX_VALUE
3.Literals
        Literals (often referred as a constant) are data items that have fixed data
values.
  Java allows several kids of literals. They are:
    Integer literals
    Floating literals
    Character literals
                                               38
    String literals
    boolean literals
    null literal
Integer Literals are whole numbers without any fractional part. Eg. 453, -53556
Rules for Integer literals
     An integer constant must have at least one digit and must not contain any decimal
      point.
     It may contain either + or – sign.
     A number with no sign is assumed to be a positive number.
     Comma cannot appear in integer constant.
Floating Literal: They are also called as real literal. They are numbers having fractional
parts. They can be expressed in 2 forms. They are:
    Fractional form eg : 134.65
    Exponent Form eg : 13465E2
Boolean Literal can have only 2 values true or false.
Character literals: A character literal is any character enclosed in single quotes. Eg. ‘S’ ‘3’
‘+’
Java allows nongraphic characters in character constants. Nongraphic characters are those
characters that cannot be typed directly from keyboard. Eg. backspace, tab, carriage return
etc. They can be represented by using Escape sequences. A Escape sequences is represented
by a backslash followed by one or more characters. The following are some of the escape
sequence in java.
                                              39
String Literals
   A string is a sequence of zero or more characters enclosed by double quotes. Each
   character may be represented by an escape sequence.
   Eg. “abc” “\abc” “Ash\’s book”
5. Operators
  An operator is a symbol representing an operation. It tells the computer to perform certain
mathematical or logical operation. Operators are used in program to manipulate data and
variable. The operators can be classified into 3 broad classification. They are:
   UNARY OPERATOR                 BINARY OPERATOR                  TERNARY OPERATOR
It works on a single           It works on two operands.         It works on three operands.
operand.                       The binary operators are : It is a conditional operator
The unary operators in          Arithmetic Operators:            that
java are Increment               +-*/%                            provides a shorter syntax
operator ++: Increments         Assignment Operator              for the if..then..else
the value of the operand by       =                              statement. The ternary
1. The increment can be        Logical Operator                  operator in java is ? :
divided into 2:                 NOT ! (Unary) AND &&               (Condition ?
   Prefix Increment eg         OR ||                             Expression 1 :
:++a                           Relational Operator
   Postfix Increment            < > >= <= == !=                  Expression 2)
eg:a++                         Shorthand Operator                Eg: (a>b? c=a : c=b)
Decrement operator –- :           += -= *= /= %=
Decrements the value of
the operand by 1. The
decrement operator can be
divided into two types.
They are:
   Prefix Decrement eg: --a
   Postfix Decrement eg: a--
Logical NOT ! : eg
if(!(a>5))
                                               40
                             Precedence Of Java Operators
Sl. no    Operators (From Highest Precedence)  Associativity
   1             ()     []                       Left to Right
   2             ++     --   !                   Right to Left
   3              *    / %                       Left to Right
   4              +    -                         Left to Right
   5              >     >= <     <=              Left to Right
   6             ==    !=                        Left to Right
   7             &&                              Left to Right
   8              ||                             Left to Right
   9              ?:                             Right to Left
   10             =    += -= *= /= %=            Right to Left
                                           41
 3. Classify the following as reserve words and non-reserve words
  i) new ii) ans iii) Good iv) system v) Void vi) token
 4. What is Identifier? Give the rules for an identifier.
 5. Classify the following as valid or invalid identifier
 i) 6hgf ii) Simple_int iii) _acb iv) $abc v) Ans
 6. What is a literal? What are different types of literals in java.
 7. Name the type of literal to which the following belong
  i) 6744 ii)’A’ iii)”A” iv) 7 v) ‘7’ vi) “7” vii) 75.66 viii) false ix) “DGF”
 8. What is an operator? What are the 3 major classification of operators.
 9. Define the following: i) Unary operator ii) Binary operator ii) Ternary operator
 10. What are the classifications of Unary operator? Name all the 3 unary operators present
     in java.
 11. Explain the following: i) Arithmetic operator ii) Assignment operator iii) Relational
     operator iv) Logical operator v) Shorthand operator
 12. What is a separator? Name all the separators present in Java.
 13. Differentiate the following: i) = and == ii) ++ and -- iii) s=++a and s=a++ iv) !
     and != v) && and || vi) Unary operator and Binary operator
 14. Classify the following as unary and binary operator and also name the type of
     operator.
           i) + ii)++ iii) -= iv) *= v) = vi) != vii) % viii) > ix) ! x) –
 16. Evaluate the following based on the precedence of the operator if initial value of
           a=3b=2c=5
     i) 400 / 3 + 6 * 8 /2 - 4     ii) 400 /3.0 + 6 * 8 / 3 – 6
     iii) 30- 45 > 50 ? 60 :90 iv) 45 > 60 && 60 <70 || 30 == 50
     v) ++a + b++ * c-- + --a + --b      vi) a+= ++a + ++b * c-- + --a
17. Name the reserve word, literal, identifier, operator and separators
     i) int a = 56; ii) if( a > 50) { s= 70};
                                           42
                                                   CHAPTER 7
                                                   DATA TYPES
Data Types are means to identify the type of data and associated operations to handling it. Data types can be
classified into 2 types. They are:
  1. Primitive data type
  2. Non-primitive (Referenced) Data type
Primitive Data Type comes as a part of java compiler. Primitive data type can be classified into 2
types. They are :
    1) Numeric data type
    2) Non-numeric data type or Reference data type
Numeric Data type: They are used to store numeric literals (constants). They are further divided into 2
parts. They are:
     Integer data type : The integer data type in java are – byte, short, int and long
     Floating-point data type : The floating data type in java are – float, double
Non-numeric Data type : They are used to store character literals. They are further divided into 2. They
are :
     Character data type : The character data type in java is – char
     Boolean data type : The Boolean data type to store Boolean literals is – Boolean
Referenced Data Type: are constructed from primitive data type. These are objects, arrays and interface. A
reference datatype is used to store the memory address of an object. These variables used to store memory address
is known as reference variables and their datatype is called as a reference data type.
                                                         42
        Primitive Data Types                        Reference Data Type
1. These are basic or fundamental data         1. These are constructed from
types supported by java.                       primitive data types by the user.
2. These primitive data type variable store    2. The reference data type variable
the actual value and their operations deals    store the address or the reference of
with rvalue. eg. int, double, char.            the memory location of the actual
                                               data. eg. arrays, classes
3. Use of new operator is not required.        3. Use of new operator is required.
4. The size of these data type are fixed       4. the size of this data types are not
                                               fixed as it depends on the data
                                               member
5.They are available in all part of the        5. Their availability depends on their
program                                        scope
                                              43
         int       a       =    50;
         double    b       =    77.77;
         char      ch      =   ‘\U0000’
         String    s       =    “XYZ”
         char      z       =    ‘T’;
Data types
                                 Literals/ constant
             Identifiers
                               44
                                    CHAPTER 8
                                JAVA EXPRESSION
 An Arithmetic expression is a combination of variables, constants and operators
arranged as per the syntax of language.
  Eg: a+b-c*d/t%2
Evaluation Of Expression
 Expressions are evaluated using an assignment statement of the form
                Variable = expression
Variable is a valid java variable name. The expression is evaluated and the result is
replaced with the previous value of the variable.
Precedence Of Arithmetic operators
An arithmetic expression without any parentheses will be evaluated from left to right using
the rules of precedence of operators.
Type of Expression
Java expression can be divided into 2 types. They are:
     1. Pure Expression
     2. Impure expression
1.Pure Expression
    In a pure expression all the operands are of same data type. Pure expression can be
broadly divided into 2 types. They are:
    Pure Integer Expression
    Pure Real Expression
Pure Integer Expression : They are formed by connecting integer constants and / or
integer variables arithmetic operators.
   Eg. int a,b,c
  i) c=a+b ii) c=a+40
 Pure Real Expression : : They are formed by connecting real constants and / or real
variables arithmetic operators. (note : % is not real arithmetic operator)
  Eg. double a,b,c;
     i) c = a/b  ii)c=a+b*3.5
                                            44
2. Impure Expression
     In impure expression the operands are of mixed data type. In a impure expression one
data type is converted into another data type.
The process of converting one pre-defined type to another is called Type conversion.
There are 2 types of type conversion. They are :
       Implicit type conversion or Automatic type conversion or coercion
       Explicit type conversion
Automatic Type Conversion or Implicit type conversion or coercion
            It is performed by the compiler automatically when there are mixing of constants
and variables of different types in an expression. But during evaluation it adheres to very
strict rules of type conversion. We know that computer considers one operator at a time,
involving two operands. If the operands are of different types, then the ‘lower’ type is
automatically converted (promoted) to ‘higher’ type. If byte, short and int variables are
used in an expression, the result is always promoted to int type to avoid overflow. If a long
datatype is used in an expression, the whole expressions promoted to long. Remember all
int are considered to be integers unless they have l or L appended to it. If an expression
contains a float datatype operand, the entire expression is promoted to float. If any operand
is double, result is double.
         Example                                      Action
x=(int)7.5                     7.5 is converted to integer by truncation
a=(int)21.3/(int)4.5           Evaluated as 21/4 and the result would be 5
b=(double)sum/n                Division is done in floating point mode.
y=(int) (a+b)                  The result of a+b is converted to integers.
Z=(int)a+b                     a is converted to integer and then added to b.
                                             45
            Pure expression                            Impure Expression
In pure expressions all the operands are of In Impure expressions all the operands are
same data types.                            of different data types.
Eg, int a,b,c;                              Eg. int a; double b; long c;
    c = a+b;                                     b = a + c;
    Here the smaller data types are              Here the data types are promoted to
     promoted to higher data types by the          the required data type by the user
     java compiler. This is also called            explicitly.It is also called Type
     coercion.                                     Casting.
                                            46
Class Work
   i) Define Expression. What are the two main categories of expression?
   ii) What are the classifications of impure expression? Define each with an example.
   iii) What is type casting or type conversion?
   iv) What data type will the following expression give?
        i) int + float + double ii) char + int iii) String + char iv) int + String v) char +
        char
        vi) 34.6 + ‘A’ vii) false + “ABC” viii) false + ‘D’
   v) float a = 4.5 + 50 *2; What type of conversion is performed in the given statement
            and what value is store in the variable?
   vi) int a = (int) 40/3; What type of conversion is performed in the given statement and
            what value is store in the variable?
   vii) Classify the following as pure and impure expression.
             a) int + char b) char + float c) int + int d) float + float
                                            47
                                               CHAPTER 3
                                              CLASS MATH
The Math class contains all the floating-point functions that are used for geometry and trigonometry.
Math defines 2 double constants: E(approximately 2.72) and PI(approximately 3.14). It is present in the
default package java.lang.
Trignometric functions
Sl.no Method Syntax                        Description
1        double = Math.sin(double)         Returns the sine of the angle specified by arg in radians
2        double = Math.cos(double)         Returns the cosine of the angle specified by arg in radians
3        double = Math.tan(double)         Returns the tangent of the angle specified by arg in radians
Exponential Functions
Sl.no Method Syntax                               Description
2       double=Math.log(double)                   Returns natural logarithm of the argument
3       double=Math.pow(double y,double x)        Returns y raise to x
4       double=Math.sqrt(double )                 Returns the square root of the positive argument
5.      double=Math.cbrt(double)                  Returns the cube root of a positive or negative
                                                  argument. Eg. 3  8 =-2
Rounding Functions
Sl Method Syntax                          Description
no
1   int=Math.abs(int)                     Returns the absolute value of argument
2   long=Math.abs(long)                   Returns the absolute value of argument
3   float=Math.abs(float)                 Returns the absolute value of argument
4   double=Math.abs(double)               Returns the absolute value of argument
5   double=Math.ceil(double)              Returns the next highest whole number greater then or equal to
                                          argument
6    double=Math.floor(double)            Returns the lowest whole number less than or equal to
                                          argument
7    int=Math.max(int x, int y)           Returns the maximum of x and y
8    long=Math.max(long x, long y)        Returns the maximum of x and y
9    float=Math.max(float x, float y)     Returns the maximum of x and y
10   double=Math.max(double x,            Returns the maximum of x and y
     double y)
11   int =Math.min(int x,int y)           Returns the minimum of x and y
12   long =Math.min(long x,long y)        Returns the minimum of x and y
13   float =Math.min(float x,float y)     Returns the minimum of x and y
14   double =Math.min(double x,           Returns the minimum of x and y
     double y)
15   int=Math.round(float)                Returns arg rounded upto the nearest int
16   long=Math.round(double)              Returns arg rounded upto the nearest long
17   double=Math.random()                 Returns a pseduorandom number between 0and 1
18   double=Math.rint( double)            Returns double value to the nearest argument
                                                   52
Difference between rint() and round()
                  round()                                               rint()
     It returns an int or long value                    It returns a double value
       i)long r =Math.round(8.7);                         double r =Math.rint(8.7);
         Output : 9                                       Output : 9.0
       ii)int r =Math.round(8.7f );
         Output : 9
      When the argument is exactly                      When the argument is exactly
       halfway between two integers it                    halfway between two integers it
       rounds up in the normal way.                       rounds to an even integer.
       i)long r =Math.round(8.5);
         Output : 9                                       double r =Math.rint(8.5);
                                                          Output :8.0
       ii)int r =Math.round(8.5f );
         Output : 9
Program 1
// Example on trigonometric function
class math
 {
       public static void main(String args[])
        {
                double sin,cos,num,num1,rad;
                num=30;
       // All trigonometric functions works on radians. So the angle should be converted to radians
                rad = num/180.0*Math.PI;
                System.out.println("radians ="+ rad);
                                                     53
  double log,pow, absfloat,absdouble,maxdou,mindou;
  int absint, maxint,minint;
  long abslong,maxlong,minlong;
  float maxflo,minflo;
  // To find logarithm of 4.222
  log = Math.log(4.22);
  System.out.println("Logarithm of 4.22 = "+ log);
                                                54
   // To find minimum of 2 long integers
      minlong = Math.min(507889,844459990);
      System.out.println("Minimum of 2 long integers = "+ minlong);
     floor = Math.floor(5.6);
     System.out.println("Floor of 5.6 = "+ floor);
     ceil = Math.ceil(5.6);
     System.out.println("Ceil of 5.6 = "+ ceil);
     floor1 = Math.floor(-5.6);
     System.out.println("Floor of -5.6 = "+ floor1);
ceil1 = Math.ceil(-5.6);
                                                              55
   System.out.println("Ceil of -5.6 = "+ ceil1);
                                                   56
                            CHAPTET 5
           ERRORS IN COMPUTER PROGRAMMING
Bug is an error in a program. Removing an error is called debugging.
Programming errors can broadly be divided into 3. They are :
    Compile-time errors : These are the errors resulting out of
       violation of programming language’s grammar rule. They are also
       called Syntax error. They are reported during compilation time.
       Eg. for(i=0, i<5, i++).
                                 57
                                    CHAPTER 4
                         ITERATION / LOOPING STATEMENTS
The Iterations are also called as Loop or Looping statements. The loops are used when we need to
repeat the statements. Java provides 3 kinds of looping statements: for loop, while loop and do-while
loop.
Elements that control a Loop:
     Initialization : The control variable must be initialized before entering the loop. This
         statement(s) is executed only once, before the loop begins.
     Test Expression (condition): the test expression decides whether the loop-body will be
         executed or not. If the condition is true then the loop is executed else the loop is terminated.
     Update Expression(s): The update expression(s) change the value(s) of the loop variable(s)
     Body-of-Loop: The statement that are executed repeatedly forms the body of the loop.
   While loop
      Program to print XYZ 5 times
      class Loop1
       { public void main()
          {int c;
           c=1;
           while(c<=5)
            {
              System.out.println("XYZ");
             c= c +1;
            }
        }}
      Output
        XYZ
        XYZ
        XYZ
        XYZ
        XYZ
Working/dry run: c =1
     Slno            while(c<=5)          System.out.println(“XYZ”)                    C=C+1
   1              while(1<=5) true       XYZ                                       2=1+1
   2              while(2<=5) true       XYZ                                       3 =2+1
                                                    21
     3             while(3<=5) true         XYZ                                 4=3+1
     4             while(4<-5) true         XYZ                                 5=4+1
     5             while(5<=5) true         XYZ                                 6=5+1
     6             while(6<=5) false       Won’t enter the loop (control is transferred outside
                                          the loop
Explanation : Initially c takes the value 1 then it checks for the condition i.e is c <= 5 and the
condition returns true. As the condition is true the control enters the body of the loop and prints
“XYZ” once. Then the control goes to c=c+1, where the value of c is incremented by 1. When the
control comes to the closing bracket the control goes back to the condition (as it is a looping
statement ) and check for the condition again. The process repeats until the condition is false. When
the condition is false the control is transferred to the statement after the loop. As there is no other
statement after the loop, program ends. As the condition is checked at the beginning of the loop while
is called Entry Control loop.
Do-while loop
       Program to print XYZ 5 times
       class Loop1
        { public void main()
           {int c;
            c=1;
            do
             {System.out.println("XYZ");
              c=c+1;’
             } while(c<=5) ;
         }}
                  Output
                    XYZ
                    XYZ
                    XYZ
                    XYZ
                    XYZ
Working/Dry run c=1
     lno        System.out.println(“XYZ”)              C=C+1             while(c<=5)
      1                     XYZ                        2=1+1           while(2<=5) true
      2                     XYZ                        3 =2+1          while(3<=5) true
      3                     XYZ                        4=3+1           while(4<=5) true
      4                     XYZ                        5=4+1           while(5<=5) true
      5                     XYZ                        6=5+1           while(6<=5) false
Explanation : Initially c takes the value 1 then it prints “XYZ” once. Then the control goes to c=c+1,
where the value of c is incremented by 1. Then it checks for the condition i.e is i<=5 and the condition
returns true. As the condition is true the control enters the body of the loop again. The process repeats
until the condition is false. When the condition is false the control is transferred to the statement after
the loop. As there are no other statements after the loop the program ends. As the condition is checked
at the end of the loop do-while is called Exit Control loop.
                                                    22
for Loop- Fixed Number Of Iterations
 It works as Entry control loop.
     In for loop all the elements(initial value ; test expression; update expression) of the loop are in
     one statement.
                Syntax
                    for(initial value ; test expression; update expression)
                             {
                                  …………..
                                  …………..
                               }
                    }
               }}
                        Output
                         XYZ
                         XYZ
                         XYZ
                         XYZ
                         XYZ
   Explanation :
     c=1 (Initialization expression) c<=10 (test expression) c=c+1 (update expression)
   1. Firstly, initialization expression is executed ci=1) which gives the first value to the variable.
   2. Then, the test expression is evaluated (c<=10) which results true
   3. since the test expression is true, the body of the loop is executed which prints the current value
       of c.
   4. The update expression (c=c+1) is executed which increments the value ofci (c becomes 2).
   5. test expression is again evaluated. If it is true the sequence is repeated from step 3 , else the
       loop terminate.
In the above the fourth (iv) example is also called Infinite loop.
                                                   23
           Entry controlled Loop                                   Exit Controlled Loop
      While is an entry controlled loop because              Do-while is an exit controlled loop
       it checks for the condition before it enters            because it executes the statements in the
       the loop. If the condition is satisfied then            body of the loop first and then it checks
       the statements in the loop is executed as               for the condition. It will execute the
       long as the condition is satisfied /true.               statements and then checks for the
                                                               condition. Depending on the condition
      It will not execute the statements in the               the loop is repeated as long as the
       loop even once if the condition is false.               condition is satisfied.
Jump Statement
 This statements transfers the control from one part of the program to another part. There are 3 jump
statements in java. They are: break, continue and return
               Break                             continue                           return
This statement terminates the This statement continues with This statement transfers the
loop.                               the next iteration in the loop     control back to the calling
Eg:                                 Eg:                                function.
 for(int i=1;i<=5;i++)              for(int i=1;i<=5;i++)
       { if(i==3)                          { if(i%2==0)                This will be done in the
           break;                              continue;               chapter constructor and
          else                                else                     methods.
           system.out.println(i);              system.out.println(i);
        }                                   }
                                                      24
// Accept a name. Print it 5 times
   import java.util.*;
   class count1
    { public static void main(String args[])
      { Scanner sc = new Scanner(System.in);
        int c; String name;
        System.out.println("Enter your name:");
        name=br.nextLine();
       c=1;
        while(c<=5)
        { System.out.println(name);
         c=c+1;
     }} }
//Accept Radius and calculate area of circle.      //Accept radius. Calculate area of circle.
Repeat the whole process 5 times.                  Repeat the whole process n times
import java.util.Scanner;                          import java.util.Scanner;
class test                                         class test
 { public static void main(String args[])           { public static void main(String args[])
    { Scanner sc = new Scanner(System.in);             { Scanner sc = new Scanner(System.in);
     double rad, ar;                                    double rad, ar;
     int c;                                             int c,n;
     c=1;                                               System.out.println("enter value for n");
     while(c<=5)                                        n=sc.nextInt();
     { System.out.println("Enter radius");              c=1;
        rad=sc.nextDouble();                            while(c<=n)
        ar=Math.PI*rad*rad;                             { System.out.println("Enter radius");
        System.out.println("area is :"+ar);                rad=sc.nextDouble();
        c=c+1;                                             ar=Math.PI*rad*rad;
      }                                                    System.out.println("area is :"+ar);
   }                                                       c=c+1;
}                                                        }
                                                      }
                                                   }
                                                  25
//Accept Principal, time and rate.                 //Accept Principal, time and rate.
Calculate simple interest and print all            Calculate simple interest and print all
the information in a neat format. Repeat           the information in a neat format. Repeat
the whole process in a neat format.                the whole process n times
import java.util.Scanner;                          import java.util.Scanner;
class test                                         class test
 { public static void main(String args[])           { public static void main(String args[])
    { Scanner sc = new                                 { Scanner sc = new
Scanner(System.in);                                Scanner(System.in);
     double pr,t,r,si;                                  double pr,t,r,si;
     int c;                                             int c,n;
     c=1;                                               System.out.println("Enter principal");
     while(c<=5)                                        n=sc.nextInt();
     { System.out.println("Enter                        c=1;
principal");                                            while(c<=n)
       pr=sc.nextDouble();                              { System.out.println("Enter
       System.out.println("Enter time");           principal");
       t=sc.nextDouble();                                 pr=sc.nextDouble();
       System.out.println("Enter rate");                  System.out.println("Enter time");
       r=sc.nextDouble();                                 t=sc.nextDouble();
       si=pr*t*r/100;                                     System.out.println("Enter rate");
       System.out.println("Principal is                   r=sc.nextDouble();
"+pr);                                                    si=pr*t*r/100;
       System.out.println("Time is "+t);                  System.out.println("Principal is
       System.out.println("Rate is "+r);           "+pr);
       System.out.println("simple Interest                System.out.println("Time is "+t);
is :"+si);                                                System.out.println("Rate is "+r);
       c=c+1;                                             System.out.println("simple Interest
     }                                             is :"+si);
   }                                                      c=c+1;
}                                                       }
                                                      }
                                                   }
 a) Write a java program to accept length and breadth. Calculate area of Rectangle. Print area of
    Rectangle.
    i)     Repeat the whole process 7 times
    ii)    Repeat the whole process n times
                                                 26
 b) Write a program to Create a class named “Student” to accept Roll number, name, marks in
    English, maths and computers. Calculate total and average. Find the result based on the
    condition:
                        Average          Result
       >=80                              “Distinction”
       >=60 and <80                      “First Class”
       >=40 and <60                      “II Class”
       Else                              “Distinction”
       Print the result in the following format:
              Roll number is -------- name is ------
             Marks in English is ----- Maths is ----- Computers is -----
             Total is ---- average is -----
             Result is -------
    iii)     Repeat the whole process 5 times
    iv)      Repeat the whole process n times
 c) **Accept empno, name and salary for 10 customers. If salary <=10000 then bonus = 15% of
    salary. If salary>10000 and salary<30000 then bonus = 20% of salary else bonus = 30% of
    salary. Print employee number, name, salary and bonus.
  d) **Create a class named “Electricity” to accept Meter numbers, Name of the consumer, Previous
meter reading and the present meter reading. Calculate Units Consumed and cost based on the
following condition :
  If UC <=100 then cost if 80p per unit
       If UC>100 and <=200 then cost is Rs 120+60p for every unit greater then 100
       If UC >200 and less then 300 then cost is Rs 230+ 50p for every unit greater than 200 else cost
    is Rs.340+ 30p for every unit greater then 300
    Print all the details in a neat format:
          Meter Number is ----- Name is ----- Previous meter reading ----- Present meter reading -----
          Units Consumed is ---- Cost is -----
    Repeat the whole process n times
f) **Accept telephone number, name and number of calls. If the number of calls is less than 100 then
charges=Re1. per call. If the number of calls is >100 and <=200 then charges = plus+0.80p for calls
greater than 100 else charges =plus+1.20 for calls greater than 200. Print telephone number, name,
number of calls and charges. Repeat the process 3 times
 d) **Write a program to accept name and height of a person. If the height is <=5ft then Print “You
    are a short person”. If the height is >5ft and height <=5.5ft then print “Your height is medium”
    else print “You are a tall person”. Repeat the whole process n times
Print the odd problems using while and even problems using do-while
   1. 5 5 5 5 5
   2. 1 2 3 4 5
   3. 5 4 3 2 1
        1 1 1 1 1
   4.
        1 2 3 4 5
        1 1 1 1 1
   5.
        2 4 6 8 10
                                                 27
6. 2       4  6 8 10
       3   6 9 12 15
7. 2      4    6 8 10
      15 12 9 6           3
8. 1 2 3 4……n
9. 2 2 4 2 6 2 8 2 10 2
10. 1x2 2x3 3x4 4x5 5x6
11. 1+3 2+5 3+7 4+9 5+11
12. x1 x 2 x 3 x 4 x 5
13. 2x3x4 4x6x8 6x9x12 8x12x16 10x15x20
14. 1x1=1      15. 2x1=2
    1x2=2          2x2 =4
    .              .
    .              .
    1x10=20        2x10=20
15. Accept n and print 10 multiples of it in table form
16.       Number        Square Cube
            1             1       1
            2             4       8
            .             .       .
            .             .       .
            n
17. Accept a number and print 10 multiples of the same in table form
18. Accept 2 number and print all the alternate number from the first number to second number
19. 0 1 1 2 3 5 8 ……….50 terms (To be done in the Practical Record)
20. 0 3 8 15 24 ……… n terms (To be done in the Practical Record)
                                             28
                                          Chapter 9
                                         Nested Loops
A loop which contain another loop in its body is called Nested Loop.
break statement : If a break statement is used in nested loop it comes out of the inner most loop.
Similarly, if continue is used in nested loops it continues with the inner most loop. To come out of a
outer most or particular loop/ to continue with the outer most loop we use labels.
Labels : In java we can label a block or statements. A label should be a valid identifiers.
In following program the label name is outer
                          while(true)
                           { …..
                                                   47
                               ASSIGNMENT ON NESTED LOOP
viii) 1 1 12 13 14 21 22 23 2 4 31 32 33 34 4 1 42 4 3 4 5
ix) 111 121 131 141 212 222 232 2 42 313 323 333 343
Give the output of the following program. Also, how many times is the loop k executed.
   { int i,k;
       for(i=1;i<4;i++)
        { for(k=1;k<5;++k)
           {
             System.out.print(k+i);
           }
        System.out.print("\n");
    }}
Find the sum of the following program
   1) S=1+1+2+1+2+3+1+2+3+4+1+2+3+4+5
   2) S=1+2+2+3+3+3+4+4+4+4+5+5+5+5+5
                                                     48
  3) S=1+2+1+3+2+1+4+3+2+1+5+4+3+2+1
  4) S=5+5+5+5+5+4+4+4+4+3+3+3+2+2+1
  5) S=1+2+3+1+2+3+1+2+3+1+2+3+1+2+3
           1 2 3 4 5
  6) S     
           1! 2! 3! 4! 5!
           1 2 3 4 n
  7) S     ....
           1! 2! 3! 4! n!
           x x2 x3 x4                xn
  8) S                  ........
           1! 2! 3! 4!               n!
           1 2 3 4                 n
  9) S     ...........
           1! 2! 3! 4!             n!
              1     2     3    4
            x     x     x    x        xn
  10) S                   .......
            1! 2! 3! 4!               n!
Application of Nested Loops
  a) Write a program to print 10 multiples of all the tables from 1 to 5.
  b) Write a program to calculate simple interest for rate being constant 4.5% and principal varying
      from 1000 to 10000 in steps of 1000 and time varying from 1 to 5 years. Also, print the result
      in the following format:
   c) Write a program to simulate tossing of a coin 10 times; 100 times and 1000 times. Keep a
      count of number of heads and tails for each of the group.
   d) Three natural numbers a,b and c are said to from a Pythagorean triplet, if a 2  b 3  c 2 . Write a
      program to print all the Pythagorean triplet from 1 to 50.
                                                   49
          I
          I C
          I C S
          I C S E
      For an incorrect option, an appropriate error message should be displayed.
***********************************************************************
                                             50
ASSIGNMENTS ON NESTED LOOPS
1)2 4 6 8 10       2) 5 5 5 5 5 5      3) 22   20   18   16   14          4) 51 51 51 51
  2 4 6 8 10         7 7 7 7 7 7         22    20   18   16   14            53 53 53 53
  2 4 6 8 10         9 9 9 9 99          22    20   18   16   14            55 55 55 55
                                         22    20   18   16   14
1)5 7 9 11                 2) 8 10 12 14                      3) 15 17 19 21          4) 21 23 25
  5 7 9                       10 12 14                          17 19 21                21 23
  5 7                         12 14                             19 21                   25
  5                           14                                21
5 5 5 5 5                  12 12 12 12                        8                       1
7 7 7 7                    14 14 14                           10 10                   333
9 9 9                      16 16                              12 12 12                55555
11                         18                                 14 14 14 14             7 777777
*   ** * *                 * * * * *                          *                       ** * *
*   ** * *                 * * * * *                          * *                     ** *
*   * * * *                * * * * *                          * **                    **
*   * * * *                                                   * * * *                 *
1 2 3                      12 3 4                             1                       15
4 5 6                      3 4 5 6                            2 3                     14 13
7 8 9                      7 8 9 10                           4 5 6                   12 11 10
                                                              7 8 9 10                9 8 7 6
     1) S= 1+2+3+1+2+3+1+2+3
     2) S= 1+2+3+6+1+2+3+6+1+2+3+6+1+2+3+6
     3) S=1+1+1+3+2+2+2+6+3+3+3+9
              1 2 3 4 5
     1) s         
              1! 2! 3! 4! 5!
            x 2 x 4 x 6 x 8 x10
     2) s              
            2! 4! 6! 8! 10!
            x 2 x 4 x 6 x 8 x10 x n
     3) s                  ....
            2! 4! 6! 8! 10! n!
                                                         51
‘1                                            *
 1 * 3                                        1 2
 1 * 3 *                                      * * *
 1 * 3 * 5                                    1 2 3 4
1 2 3 4 5                                 1                             *
  1 2 3                               1   2 3                         * * *
    1                               1 2   3 4 5                     * * * * *
                          *
                     *    *   *
                 *   *    *   *   *
             *   *   *    *   *   * *
                 *    *   *   *   *
                     *    *   *
                          *
**********************************************************************************
                                            52
                                 CHAPTER 5 ACCUMULATOR
To find s= 1+2+3+4+5
 class sum
  { public static void main(String args[])
     { int c, s;
       s=0;
       c=1;
       while(c<=5)
        { s=s+c;
          c=c+1;
         }
       System.out.println("Sum is "+ s);
      }}
Dry run
Initial values : c= 1 s=0
Slno     while(c<=5)                  s=s+c             c=c+1
1        while(1<=5) true              1=0+1            2=1+1
2        while(2<=5) true              3=1+2            3=2+1
3        while(3<=5) true              6=3+3            4=3+1
4        while(4<=5) true             10= 6+4           5=4+1
5        while(5<=5) true             15=10+5           6=5+1
Problems on Summation
1. 1+2+3+4+5
2. 2+4+6+8+10
   1 1 1 1 1
3.     
   1 2 3 4 5
  1 1 1 1 1
4.    
  2 4 6 8 10
  2 4 6 8 10
5.    
  3 6 9 12 15
6. find 5!
7. Find n!
   3 X !5Y !
8.
      X !Y !
9. 1  2 3  34  4 5  56
    2
10. x1  x 2  x 3  x 4  x 5
                                             32
                              Application of Accumulator
Example 1
//Repeat constant times                     //Repeat variable times
// Accept 5 numbers and find their          // Accept n numbers and find their sum.
sum.                                        import java.io.*;
import java.util.*;                         class sum1
class sum1                                   { public static void main(String args[])
 { public static void main(String args[])      {Scanner sc = new
   Scanner sc = new                         Scanner(System.in);
Scanner(System.in);                             int c,no,sum,n;
    int c,sum;                                  System.out.println("Enter a
    sum=0; c=1;                             number:");
    c=1;                                        n = sc.nextInt();
    while(c<=5)                                 sum=0; c=1;
     { System.out.println("Enter a               while(c<=n)
number:");                                       {System.out.println("Enter a
       no= sc.nextInt();                    number:");
       sum=sum+no;                                 no = sc.nextInt();
       c=c+1;                                     sum=sum+no;
     }                                             c=c+1;
    System.out.println("The sum is               }
"+sum);                                         System.out.println("The sum is
}}                                          "+sum);
                                            }}
EXAMPLE 2
Repeat Constant times                     Repeat Variable Times
//Accept 10 numbers and find the            //      Accept n numbers and find the
number of positive numbers and sum          number of positive numbers and
of negative numbers                         sum of negative numbers
import java. util.*;                        import java.util.*;
class acc                                   class acc
 { public static void main(String args[])    { public static void main(String
   { Scanner sc = new                       args[])
Scanner(System.in);                            { Scanner sc = new
    int num,pcou=0,nsum=0,c;                Scanner(System.in);
    c=1;                                        int num,pcou=0,nsum=0,c,n;
    while(c<=10)                                System.out.println("Enter value
     { System.out.println("Enter a          for n");
number");
      num=sc.nextInt();                     n=Integer.parseInt(br.readLine());
      if(num>0)                                 c=1;
       pcou=pcou+1;                             while(c<=n)
      else if(num<0)                             { System.out.println("Enter a
                                            33
       nsum=nsum+num;                             number");
      c=c+1;                                            num=sc.nextInt();
     }                                                  if(num>0)
    System.out.println("Sum of                           pcou=pcou+1;
negative numbers is "+nsum+"                            else if(num<0)
Number of positive numbers is                            nsum=nsum+num;
"+pcou);                                                c=c+1;
  }}                                                   }
                                                      System.out.println("Sum of
                                                  negative numbers is "+nsum+"
                                                  Number of positive numbers is
                                                  "+pcou);
                                                    }}
   a) Accept 10 numbers. Find the sum of only positive numbers. Print the sum.
   b) Accept n numbers. Find the sum of only positive numbers. Print the sum
   c) Accept empno, name and salary for 50 customers. If salary <=10000 then bonus =
      15% of salary. If salary>10000 and salary<30000 then bonus = 20% of salary else
      salary = 30% of salary. Print employee number, name, salary and bonus. Also, print
      the number of employees in each category.
f) Accept Roll number , name, marks in English, Math and Computers. Calculate total and
average. Also calculate result based on the following condition :
         If average is greater than equal to 80 then return the message “Distinction”
        If the average is greater than equal to 60 and less then 80 then return the message
      “I class”
        If the average is greater than equal to 40 and less then 60 then return the message
      “II class”
              Then return the message “Fail”
        Print the result in the following format:
              Roll number is -------- name is ------
             Marks in English is ----- Maths is ----- Computers is -----
             Total is ---- average is -----
             Result is -------
  Find the number of students whose average is greater than equal to 80.
h) Write a program to determine out of n students, the number of students who have
scored greater then equal to 80, greater than equal to 60 and less then 80 and less than 60.
i) Govt. of India is interested to determine the opinion of general public about the
education policy. The response to this question is to be one of the follows:
   1 - means in favour
                                             34
  2 - means in oppose
  3 - means no opinion
Write a program to input the response of each persons, calculate the number of responses
of each type and print the them, assuming that n persons have were interviewed.
************************************************************
                                           35
                                       CHAPTER 10
                                    MODULUS OPERATOR
                                                      53
{ public static void main(String args[])
   { int no,no1, r,s;
     Scanner Sc=new Scanner(System.in);
     System.out.println("Enter a number");
     no=Sc.nextInt();
     no1=no; // To copy the original number
     s=0;
     while(no!=0)
      {r=no%10;
       s=s+r*r*r;
       no=no/10;
      }
     if(no1==s)
       System.out.println(no1+"It is an Armstrong number ");
     else
     System.out.println(no1+"It is not an Armstrong number ");
  }}
//To print all factors of a                // To count number of factors       // To add all the factors
number
import java.util.Scanner;                  import java.util.Scanner;           import java.util.Scanner;
class mod1                                 class mod1                          class mod1
 { public static void main(String           { public static void main(String    { public static void main(String
args[])                                    args[])                             args[])
    { int no,i;                                { int no,i,c;                       { int no,i,s;
      Scanner Sc=new                             Scanner Sc=new                      Scanner Sc=new
Scanner(System.in);                        Scanner(System.in);                 Scanner(System.in);
      System.out.println("Enter                  System.out.println("Enter           System.out.println("Enter
a number");                                a number");                         a number");
      no=Sc.nextInt();                           no=Sc.nextInt();                    no=Sc.nextInt();
      for(i=1;i<=no;i++)                         c=0;                                s=0;
       {if(no%i==0)                              for(i=1;i<=no;i++)                  for(i=1;i<=no;i++)
           System.out.println(i);                 {if(no%i==0)                        {if(no%i==0)
          }                                           c=c+1;                              s=s+i;
  }}                                              }                                   }
                                                                                     System.out.println("Sum of
                                           System.out.println("Number of       all the factors is "+s);
                                           factors are "+c);                     }}
                                             }}
// Application of Prime number + Nested loop – To print all prime numbers from 1 to 100
import java.util.Scanner;
class mod1
 { public static void main(String args[])
    { int no,i,c;
      Scanner Sc=new Scanner(System.in);
      for(no=1;no<=100;no++)
      { c=0;
        for(i=1;i<=no;i++)
         {if(no%i==0)
            c=c+1;
         }
       if(c==2)
        System.out.println(no+" is a prime number");
       }
  }}
// Application of prime numbers – Twin Prime 3 and 5 (both are prime numbers and the
difference between them is two)
import java.util.Scanner;
class mod1
 { public static void main(String args[])
    { int no1,no2,i,c1,c2;
      Scanner Sc=new Scanner(System.in);
      System.out.println("Enter a number");
      no1=Sc.nextInt();
     System.out.println("Enter a number");
      no2=Sc.nextInt();
      c1=0;
       for(i=1;i<=no1;i++)// count the factors of no1
         {if(no1%i==0)
            c1=c1+1;
         }
         c2=0;
       for(i=1;i<=no2;i++)// count the factors of no2
         {if(no2%i==0)
            c2=c2+1;
         }
      if(c1==2 && c2==2 && Math.abs(no1-no2) == 2)
        System.out.println(no1+" and "+ no2+" are twin prime ");
      else
        System.out.println(no1+" and "+ no2+" not are twin prime ");
  }}
// Application of Sum of Factors – Perfect Number : eg: 6 = 1+2+3=6 Sum of factors other than the
number is equal to the given number
import java.util.Scanner;
                                                   57
class mod1
 { public static void main(String args[])
    { int no,s,i;
      Scanner Sc=new Scanner(System.in);
      System.out.println("Enter a number");
      no=Sc.nextInt();
      s=0;
       for(i=1;i<no;i++) // sum of factors other than the number
         {if(no%i==0)
            s=s+i;
         }
       if(s==no)
        System.out.println(no+" is a Perferct number ");
       else
        System.out.println(no+" is not a Perferct number ");
  }}
// Application of sum of factors – Amicable Numbers-n1 and n2 are amicable numbers if, sum of
factors of n1 is equal to n2 and sum of factors of n2 is equal to n1.
import java.util.Scanner;
class mod1
 { public static void main(String args[])
    { int n1,n2,sfn1,sfn2,i;
      Scanner Sc=new Scanner(System.in);
      System.out.println("Enter a number");
      n1=Sc.nextInt();
      System.out.println("Enter a number");
      n2=Sc.nextInt();
      sfn1=0;
       for(i=1;i<n1;i++)// sum of factors of n1
         {if(n1%i==0)
            sfn1=sfn1+i;
         }
      sfn2=0;
       for(i=1;i<n1;i++)// sum of factors of n2
         {if(n1%i==0)
            sfn2=sfn2+i;
         }
       if(sfn1==n2 && sfn2==n1 && Math.abs(n1-n2)==2)
        System.out.println(n1+ " and "+ n2 +" Amicable numbers ");
       else
        System.out.println(n1 + " and "+ n2 +" are not Amicable numbers");
  }}
                                          Automorphic Number
Long and inefficient method-Works upto 3            Short and efficient method- works for any
digits                                              number of digits
import java.util.Scanner;                           import java.util.Scanner;
class mod1                                          class mod1
 { public static void main(String args[])            { public static void main(String args[])
                                                    58
  { int n1,sq,r=0;                                     { int n1,sq,n2,c=0,r;
    Scanner Sc=new Scanner(System.in);                   Scanner Sc=new Scanner(System.in);
    System.out.println("Enter a number");                System.out.println("Enter a number");
    n1=Sc.nextInt();                                     n1=Sc.nextInt();
    sq=n1*n1;                                            n2=n1;
    if(n1>1 && n1<10)                                    c=0;
     r=sq%10;                                            while(n1!=0)
    else if(n1>9 && n1<=99)                               {c=c+1;
     r=sq%100;                                             n1=n1/10;
    else if(n1>99 && n1<=999)                             }
     r=sq%1000;                                          sq=n2*n2;
    if(r==n1)                                            r=sq%(int)Math.pow(10.0,(double)c);
      System.out.println(n1+" is an Automorphic          if(r==n2)
number");                                                  System.out.println(n2+" is an Automorphic
     else                                            number");
      System.out.println(n1 + "is not an                  else
Automorphic number");                                      System.out.println(n2 + "is not an
 }}                                                  Automorphic number");
                                                      }}
      if(s==n2)
        System.out.println(n2+" is a Strong number");
       else
        System.out.println(n2 + " is not a Strong number");
 }}
                                                     60
To convert Decimal number to Binary number (Not in syllabus)
// Convert decimal to binary equvalent
import java.util.Scanner;
class st1
 {
         public static void main(String args[])throws IOException
          {
                  int dnum,i,k,r,t;
                  int bnum[]=new int[15];
             t=dnum;
             i=0;
             while(dnum!=0)
              {
                  r=dnum%2;
                  bnum[i]=r;
                  i++;
                  dnum=dnum/2;
              }
             System.out.print("Binary equivalent of "+ dnum +" is ");
             for(k=i-1;k>=0;k--)
              System.out.print(bnum[k]);
        }}
// To accept 2 number and print their highest common factor and their lowest common factor
import java.io.*;
class m1
 { public static void main(String args[])
          {
          int n2,n1,sn,lcm,hcf=0,i;
            Scanner Sc=new Scanner(System.in);
         System.out.println("Enter a number");
         n1=Sc.nextInt();
         n2=Sc.nextInt();
          sn=Math.min(n1,n2);
            for(i=1;i<=sn;i++)
              {
                if(n1%i==0 && n2%i==0)
                 hcf=i;
              }
             lcm=(n1*n2)/hcf;
                                                     61
           System.out.println("The HCF of "+n1+" and "+ n2 +" is "+hcf);
           System.out.println("The LCM is "+n1+" and "+ n2 +" is "+lcm);
 }}
int n,n1,r,s=0;
           n1=n;
            while(n!=0)
            {
                 r=n%10;
                 if(r==1 || r==2 || r==3 || r==5 || r==7)
                   s=s+r;
                 n=n/10;
           }
           System.out.println("The sum of all prime digits in "+n1+" is "+s);
          }}
/*The International Standard Book Number (ISBN) is a unique numeric book identifier which is printed
on every book. The ISBN is based upon a 10-digit code. The ISBN is legal if 1*digit1 + 2*digit2 + 3*digit3
+ 4*digit4 + 5*digit5 + 6*digit6 + 7*digit7 + 8*digit8 + 9*digit9 + 10*digit10 is divisible by 11.
Example: For an ISBN 1401601499
Sum=1*1 + 2*4 + 3*0 + 4*1 + 5*6 + 6*0 + 7*1 + 8*4 + 9*9 + 10*9 = 253 which is divisible by 11.
Write a program to:
(i) input the ISBN code as a 10-digit number
(ii) If the ISBN is not a 10-digit number, output the message “Illegal ISBN” and terminate the program
(iii) If the number is 10-digit, extract the digits of the number and compute the sum as explained above.
*/
import java.util.Scanner;
 class ISBN
  {public static void main(String args[])
   {Scanner sc = new Scanner(System.in);
       long c=0,i,s=0; long r,rn=0,n,n1;
       System.out.println("Enter a number");
       n = sc.nextLong();
       n1=n;
       while(n1!=0)
        { r=n1%10;
                                                     62
        rn=rn*10+r;
        n1=n1/10;
        }
        System.out.println("Reverse="+rn);
       for(i=1;i<=10;i++)
       { r=rn%10;
          s=s+r*i;
          rn=rn/10;
       }
       System.out.println("sum="+s);
       if(s%11==0)
          System.out.println("It is an ISBN number");
       else
        System.out.println("It is not an ISBN number");
       }
  }
import java.util.Scanner;
 class GCD
  {public static void main(String args[])
   {Scanner sc = new Scanner(System.in);
     int n1,n2,hn,sn,r;
     System.out.println("Enter a number");
     n1 = sc.nextInt();
     System.out.println("Enter another number");
     n2 = sc.nextInt();
     if(n1>n2)
      { hn=n1; sn=n2;}
     else
       { hn=n2; sn=n1; }
       while(true)
        { r=hn%sn;
         if(r==0)
           break;
         hn=sn;
         sn=r;
       }
       System.out.println("GCD ="+sn);
  }}
Question 2 (2015)
Using the switch statement, write a menu driven program to:
   i) To find and display all the factors of a number input by the user( including 1 and
       excluding number itself).
       Example :
       Sample Input         :      n=15
       Sample output        :1,3,5
ii) To find and display the factorial of a number input by the user( the factorial of a non-
negative number n, denoted n by n!, is the product of all integers less than or equal to n.
Examples :
 Sample Input         : n=5
Sample Output : 5! = 1x2x3x4x5 = 120
For an incorrect choice, an appropriate error message should be displayed.
Question 3 (2014)
A special two-digit number is such that the sum of its digits is added to the product of its
digits, the result is equal to the original two-digit number.
Example :       Consider the number 59.
                Sum of digits = 5+9 = 14
                Product of it digits = 5x9 = 45
                Sum of sum of digits and product of digits = 14 + 45 = 59
Write a program to accept a two-digit number. Add the sum of its digits to the product of its
digit. If the value is equal to the number of input, output the message “Special 2-digit
number” otherwise, output the message “Not a special 2-digit number”.
Question 4
Write a program to accept a number and check if the first and the last digit of the number
are same or not. Note: The number can have any number of digits.
Example : Input: Enter a number : 343
Output : They are same
                                                64
Question 5 (2017)
Write a program to accept a number and check and display whether it is a SPY number or
not. (A number is a spy if the sum of its digits equals the product of its digits).
Example : Consider the number 1124         Sum of digits = 1+1+2+4=8
                                         Product of digits = 1x 1x2x4=8
Question 6 ( 2018)
Question 7(2019)
A tech number has even number of digits. If the number is split in two equal halves, then the
square of sum of these halves is equal to the number itself. Write a program to generate and
print all the four digits tech numbers.
Example:
Consider the number 3025
Square of sum of the halves of 3025 = (30+25)2
                                    = (55)2
                                     =3025 is a tech number
*******************************************************************************
65