Chapter Two
Chapter Two
                             1                         8/5/2025
              Outline
o   Identifiers
o Keywords
o Input/output
o Variables
o Data Types
o Operators
o Precedence of operators
o Statements and Blocks
o Control structure
                            2   8/5/2025
               Simple Java Program
Step 1 ) Copy the following code into a notepad.
oThe   JVM loads the class specified by Class Name and uses that class name to
 invoke method main.
oDeclaring   main as static allows the JVM to invoke main without creating an
                                          5                              8/5/2025
 instance of the class.
                    Java Keywords
✓Keywords are predefined identifiers reserved by Java for a specific purpose.
✓These keywords cannot be used as names for a variable, class or method [Identifiers].
                                             6                                  8/5/2025
                     Java Identifiers
o Identifiers are tokens that represent names of variables, methods, classes,
 packages and interfaces etc.
  • An identifier must start with a letter, an underscore (_), or a dollar sign ($).
  • It cannot start with a digit.
  • An identifier cannot be a reserved word.
  • An identifier cannot be true, false, or null.
  • An identifier can be of any length.   7                                 8/5/2025
                         Java Literals
o Literals are tokens that do not change or are constant.
o The different types of literals in Java are:
   • Integer Literals: decimal (base 10), hexadecimal (base 16), and octal (base 8).
            Example: int x=5; //decimal
   • Floating-Point Literals: represent decimals with fractional parts.
            Example: float x=3.1415;
   • Boolean Literals: have only two values, true or false (0/1).
            Example: boolean test=true;
   • Character Literals: represent single Unicode characters. A Unicode character is a 16-
     bit character set that replaces the 8-bit ASCII character set.
            Example: char ch=‘A’;
   • String Literals: represent multiple/sequence of characters enclosed by double quotes.
            Example: String str=“Hello World”;
                                                  8                                8/5/2025
                        Java Comments
▪ Java comments   are notes written to a code for documentation purposes.
▪ Comment texts are not part of the program and compiler ignores executing them.
3. Documentation Comments: The documentation comment begins with a /** and ends
with a */.
                                         10                         8/5/2025
                 Java Input Statements
o Scanner and BufferedReader class are used to accept data from user/keyboard.
o Scanner class
  • Java provides various ways to read input from the keyboard, the java.util package
  • Reads input from the user and pass the input stream (System.in) in the
    constructor of Scanner class.
             Scanner in = new Scanner(System.in);
                                           11                               8/5/2025
import java.util.Scanner;
public class javaIO
{
public static void main(String[] args) {
     String name;
     int x;
     double y;
    Scanner input = new Scanner( System.in ); //obtain input from command window
    System.out.println("Enter Your Name: "); //prompt user to enter name
     name= input.nextLine(); // Obtain user input(line of text/string) from keyboard
     System.out.println("Enter x, y:"); //prompt user to enter values of x & y
     x= input.nextInt(); // Obtain user integer input from keyboard
     y= input.nextDouble(); // Obtain user double input from keyboard
    System.out.println("Your Name is: "+name);
    System.out.println("The Value of x is: "+x);
    System.out.println("The Value of y is: "+y);
}
                                                     12                                8/5/2025
}
o BufferedReader
  ▪ Reads   text from a character-input stream to provide efficient reading of
   characters, arrays, and lines.
  ▪ It can be used to read data line by line by readLine() method and makes the
   performance fast.
                                             13                              8/5/2025
//Accepting inputs using BufferedReader
   import java.io.BufferedReader;
   import java.io.IOException;
   import java.io.InputStreamReader;
   public class javaIO {
   public static void main( String[] args )throws IOException
   {
   String name;
   int age;
   String str;
   BufferedReader br= new BufferedReader(new InputStreamReader( System.in) );
   System.out.print("Please Enter Your Name:");
   name=br.readLine();
   System.out.print("Please Enter Your Age:");
   str=br.readLine();      //to read an input data
   age=Integer.parseInt(str);      //convert the given string int to integer
   System.out.println("Hello "+ name +"! Your age is: "+age);
                                                     14                         8/5/2025
   }   }
                    Data Types in java
o   Data types specify the different sizes and values that can be stored in the variable.
        ▪   They are the building blocks of data manipulation and cannot be further divided
            into simpler data types.
▪ Example: Boolean, char, byte, short, int, long, float and double.
             }
                         Java Operators
o An operator is a symbol that operates on one or more arguments to produce a
 result.
                                                                                   8/5/2025
                                             21
                Demo. of arithmetic operators
public class ArithmeticOperators
x <= y Less than or equal to True if x is less than or equal to y, otherwise false.
x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.
      }
                     Logical operators Demonstration 2
import java.util.Scanner; //import statement for accepting input from keyboard
public class LogOps {
public static void main(String[] args) {
      double mark;
      Scanner input = new Scanner( System.in ); //Create Scanner to obtain input from command window
      System.out.println( "Enter Student Mark: "); // prompt user to enter mark
      mark = input.nextDouble(); // obtain user input from keyboard
 if(mark<0 || mark>100) {
   System.out.println("Invalid Input! Mark Must be between 0 & 100");
  }
 else if(mark>80 && mark<=100) {
   System.out.println("A");
  }
 else if(mark>=60 && mark<80) {
   System.out.println("B") ;
  } else {
  System.out.println(“F");
                                                    26                                     8/5/2025
 } }}
             Increment & Decrement Operators
o The auto increment (++) and auto decrement (--) operators provide a convenient
 way of, respectively, adding and subtracting 1 from a numeric variable.
o When used in prefix form, the operator is first applied and the outcome is then
 used in the expression.
o When used in the postfix form, the expression is evaluated first and then the
 operator applied.          Example: int k=5;
                                                27                            8/5/2025
      Illustration of increment & decrement operators
public class IncDec
{
public static void main(String[] args)
{
int num;
num = 10; // assign 10 to num
System.out.println(num );       // prints 10
System.out.println(++num ); // prints 11 (Prefix)
System.out.println(num );       // prints11
                                                     Program Output
System.out.println(num++ ); // prints 11 (Postfix)     10
System.out.println(num );       // prints 12           11
                                                       11
}
                                                       11
}                                                      12
                                               28               8/5/2025
              Precedence of Java operators
o The order in which operators are evaluated in an expression is significant and is
  determined by precedence rules.
                                         29                               8/5/2025
30   8/5/2025
Example
public class OperatorPrecedence
{
                                                       Output
public static void main(String[] args)
                                                           a+b/d = 20
{
                                                           a+b*d-e/f = 219
int a = 20, b = 10, c = 0;
int d = 20, e = 40, f = 30;
// (* = / = %) > (+ = -) precedence rules
System.out.println("a+b/d = " + (a + b / d));
System.out.println("a+b*d-e/f = "+ (a + b * d - e / f));
    }
    }
                                         31                             8/5/2025
               Java Statements & Blocks
▪ A statement is one or more line of code terminated by semicolon (;).
           Example:         int x=5;
                           System.out.println(“Hello World”);
▪ A block is one or more statements bounded by an opening & closing curly braces
 that groups the statements as one unit.
 Example: public static void main(String args[]) {
                int x=5;
                int y=10;
               char ch=‘Z’;
               System.out.println(“Hello ”);
               System.out.println(“World”);            //Java Block of Code
               System.out.println(“x=”+x);
               System.out.println(“y=”+y);
               System.out.println(“ch=”+ch);32                                8/5/2025
           }
                 Simple Type Conversion/Casting
o Type casting enables to convert the value of one data from one type to another type.
       (int) 3.14;    // converts 3.14 to an int to give 3
      (double) 2;     // converts 2 to a double to give 2.0
      (char) 122;     // converts 122 to a char whose code is 122 (z)
Example
public class TypeCasting {
public static void main(String[] args) {
    float x=3.14;
    int ascii = 65;
   System.out.println(“Demonstration of Simple Type Casting");
   System.out.println((int) x);          //3
   System.out.println((long) x);          //3
   System.out.println((double) x); //3.0
   System.out.println((short) x);         //3
   System.out.println((char) ascii); //A
} }
                                                                   33              8/5/2025
               Java control statements
oThe statement is the instruction given to the computer that performs specific types of
 work. They can make decisions and repetitive tasks.
❖ if statement
o The if-statement specifies that a statement (or block of code) will be executed if
 and only if a certain boolean statement is true.
o Syntax: if(condition)
statements;
o The first expression is evaluated. If the outcome is true then statement is executed.
 Otherwise, nothing happens.
o Example: When dividing two values, we may want to check that the denominator
 is nonzero. if(y!=0)
                                           35
               div=x/y;
❖   if-else statement
                                              37
                                                   }
                        switch statement
o The switch statement used to select one of many code blocks to be executed.
   • The switch expression is evaluated once.
   • The value of the expression is compared with the values of each case.
   • If there is a match, the associated block of code is executed unless the default
    statement is executed .
o Syntax:
     switch(expression)
     {
     case label: // code block
     break;
     case label: // code block
     break;
                                           38
     default: // code block }
               Demonstration of switch statement
int day = 4;
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
                                                   Output
break;
                                                     Thursday
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
default:
System.out.println("Sunday");
                                           39
}
40
                  Looping Statements
▪ Looping statements are Java statements that allows to execute specific blocks
 of code a number of times.
▪ Entry   controlled loop: The loop in which test condition is checked in the
 beginning of the loop.
▪ Exit controlled loop: when statements inside the loop body is executed and
 then the condition is checked that loop.
  • The loop will stop the execution if the testing expression evaluates to false.
  • Syntax:
                    while(Conditions)
                           { // code block to be executed
                           }
  •   Example: Adding the first 10 natural numbers(1-10)
                 int i=1,sum=0;
                   while(i<=10)
                    sum+=i;
                                            42
                    i++;
2) do-while Loop statement
 • The   do-while loop is similar to the while loop, except that the test
   condition is performed at the end of the loop instead of at the beginning.
 • When    the loop condition becomes false, the loop is terminated and
   execution continues with the statement immediately following the loop.
 • Syntax:
                   do
                                                                    43
Example
  public class do_while {
      public static void main(String[] args)
  {
          int i = 10;
          do
  {
              System.out.println("i is " + i);
              i++;
          }
  while (i < 5);
      }
  }
                                                 44
3) for loop statement
✓ The for loop allows execution of the same code a number of times.
✓ Syntax:     for (Initialization; Condition; Expression)
                        { // code block to be executed
                    }
   • Initialization –is executed (one time) before the execution of the code block.
   • Condition -defines the condition for executing the code block.
   • Expression - is executed (every time) after the code block has been executed
✓ Example:    int i, sum=0;                           int i;
      for (i = 1; i <= n; i++)                       for ( i = 0; i < 10; i++ )
       {                                             {
        sum += i;                                 System.out.print(i)
       }                                         }
                                                                                  45
                    Nested loop statement
oMany    applications require nesting of the loop statements, allowing on loop
 statement to be surrounded with in another loop statement.
o Nesting can be defined as the method of embedding one control structure with in
 another control structure.
o While making control structures to be reside one with in another, the inner and
 outer control structures may be of the same type or may not be of same type.
                                         46
//Nested loop demo
        public class NestedLoop
        {
        public static void main(String[] args)
        {
        int i;
        int j;
        for(i=5;i>=1;i--)                         Output
                                                     55555
        {
        for(j=1;j<=i;j++)                            4444
{ 333