Java Programming
Java Tokens & Data types
 Identifiers
• Can’t be keywords
• Case-sensitive
• Begin with and consist of:
 – Letters (a... Z)
 – Numbers (0…9) Same as C++
 – Underscore (_)
 – Dollar sign ($)
 Primitive Types
• boolean 8 bits (1 byte)
• char 16 bits (2 bytes)
• byte 8 bits (1 byte)
• short 16 bits (2 bytes)
• int 32 bits (4 bytes)
• long 64 bits (8 bytes)
• float 32 bits (4 bytes)
• double 64 bits (8 bytes)
Guaranteed to occupy same number of bits regardless of
 platform
 Strings
• Java defines the String class to handle strings
• A String is a collection of characters treated as
 a single unit
• It is not an array of char variables
• Multiple String constructors
 String s1 = new String(“Hello World”);
 String s2 = “Hello World”;
 Type Casting
• Assigning a value of one type to a variable of
 another type is known as Type Casting.
• Syntax:
 dataType variableName = (dataType) variableToConvert;
• Type casting are of two types they are
 – Implicit Casting (Widening)
 – Explicit Casting (Narrowing)
 Implicit Casting in Java /
 Widening / Automatic type conversion
• Automatic type conversion can happen if both
 type are compatible and target type is larger
 than source type.
 Explicit Casting in Java / Narrowing
• When you are assigning a larger type to
 a smaller type, then Explicit Casting is
 required.
 standard default values
In Java, every variable has a default value. If we don’t initialize a
variable when it is first created, Java provides default value to that
variable type automatically as shown in below table
 Data Type Default Value (for fields)
 byte 0
 short 0
 int 0
 long 0L
 float 0.0f
 double 0.0d
 char ‘u0000’
 String (or any object) null
 boolean false
 Java – Operators and Expressions
• The symbols which are used to perform logical and
 mathematical operations in a Java program are
 called Java operators.
• These Java operators join individual constants and
 variables to form expressions.
• Operators, functions, constants and variables are
 combined together to form expressions.
• Consider the expression A + B * 5. where, +, * are
 operators, A, B are variables, 5 is constant and A +
 B * 5 is an expression.
 Types of operators:
• Java language offers many types of operators.
 They are,
 – Arithmetic operators
 – Assignment operators
 – Relational operators
 – Logical operators
 – Bit wise operators
 – Conditional operators (ternary operators)
 – Increment/decrement operators
 – Special operators
 Arithmetic Operators in Java:
• Arithmetic operators are used to perform
 mathematical calculations like addition,
 subtraction, multiplication, division and
 modulus in Java programs.
 S.no Arithmetic Operators Operation Example
 1 + Addition A+B
 2 – Subtraction A-B
 3 * multiplication A*B
 4 / Division A/B
 5 % Modulus A%B
 Assignment Operators in Java
• In Java programs, values for the variables are
 assigned using assignment operators.
 Operators Example Explanation
 Simple assignment
 = sum = 10 10 is assigned to variable sum
 operator
 += sum += 10 This is same as sum = sum + 10
 -= sum -= 10 This is same as sum = sum – 10
 *= sum *= 10 This is same as sum = sum * 10
 Compound assignment
 /+ sum /= 10 This is same as sum = sum / 10
 operators
 %= sum %= 10 This is same as sum = sum % 10
 &= sum&=10 This is same as sum = sum & 10
 ^= sum ^= 10 This is same as sum = sum ^ 10
 Relational operators in Java
• Relational operators are used to find the
 relation between two variables. i.e. to
 compare the values of two variables in a Java
 program.
 S.no Operators Example Description
 1 > x>y x is greater than y
 2 < x<y x is less than y
 3 >= x >= y x is greater than or equal to y
 4 <= x <= y x is less than or equal to y
 5 == x == y x is equal to y
 6 != x != y x is not equal to y
 Logical operators in Java
 • These operators are used to perform logical
 operations on the given expressions.
S.
 Operators Name Example Description
no
 logical
1 && (x>5)&&(y<5) It returns true when both conditions are true
 AND
 logical It returns true when at-least one of the
2 || (x>=10)||(y>=10)
 OR condition is true
 It reverses the state of the operand
 logical “((x>5) && (y<5))”
3 ! !((x>5)&&(y<5))
 NOT If “((x>5) && (y<5))” is true, logical NOT
 operator makes it false
 Bit wise operators in Java
• These operators are used to perform bit
 operations. Decimal values are converted into
 binary values which are the sequence of bits
 and bit wise operators work on these bits.
 x y x|y x&y x^y Operator_symbol Operator_name
 0 0 0 0 0 & Bitwise_AND
 0 1 1 0 1 | Bitwise OR
 1 0 1 0 1 ~ Bitwise_NOT
 1 1 1 1 0 ^ XOR
 << Left Shift
 >> Right Shift
 Conditional or ternary operators in Java
• Conditional operators return one value if condition is
 true and returns another value if condition is false.
• This operator is also called as ternary operator.
• Syntax :
 (Condition? true_value: false_value);
• Example:
 (A >100 ? 0 : 1);
 In above example, if A is greater than 100, 0 is returned
 else 1 is returned. This is equal to if else conditional
 statements.
 Increment/decrement Operators in Java
• Increment operators are used to increase the
 value of the variable by one and decrement
 operators are used to decrease the value of the
 variable by one in Java programs.
• Syntax:
 Increment operator:
 ++var_name; (or) var_name++;
 Decrement operator:
 --var_name; (or) var_name--;
• Difference between pre/post increment &
 decrement operators in Java:
S.no Operator type Operator Description
 ++i Value of i is incremented before
 1 Pre increment
 assigning it to variable i.
 i++ Value of i is incremented after assigning
 2 Post–increment
 it to variable i.
 --i Value of i is decremented before
 3 Pre decrement
 assigning it to variable i.
 i-- Value of i is decremented after assigning
 4 Post_decrement
 it to variable i.
 Operator precedence & associativity
• Java operators have two properties those are
 precedence and associativity.
• Precedence is the priority order of an operator, if
 there are two or more operators in an expression
 then the operator of highest priority will be
 executed first then higher, and then high. For
 example, in expression 1 + 2 * 5, multiplication (*)
 operator will be processed first and then addition.
 It's because multiplication has higher priority or
 precedence than addition.
Evaluation Order of an Expression
• In Java when an expression is evaluated, there
 may be more than one operators involved in
 an expression. When more than one operator
 has to be evaluated in an expression Java
 interpreter has to decide which operator
 should be evaluated first. Java makes this
 decision on the basis of the precedence and
 the associativity of the operators.
 Mathematical Functions
• min(x,y)- Returns the minimum of the two values x and y
• max(x,y)- Returns the maximum of the two values x and y
• sqrt(x)- Returns the rounded positive square root of a value.
• pow(x,y)- Returns the value of x raised to the power of y (xy).
• exp(x)- Returns e raised to the power of x (ex).
• round(x)- Returns the closest integer to the argument x.
• abs(x)- returns the absolute value of x.
 Decision making & looping
• In decision control statements, group of
 statements are executed when condition is
 true. If condition is false, then else part
 statements are executed.
• There are 3 types of decision making control
 statements in Java language.
 – if statements
 – if else statements
 – nested if statements
 Decision Syntax Description
 control
 statements
if if (condition) In these type of statements, if
 { Statements; } condition is true, then respective
 block of code is executed.
if…else if (condition) In these type of statements, group
 { Statement1; Statement2; } of statements are executed when
 else condition is true. If condition is
 { Statement3; Statement4; } false, then else part statements are
 executed.
if else if ladder if (condition1) If condition 1 is false, then
 { Statement1; } condition 2 is checked and
 else_if(condition2) statements are executed if it is
 { Statement2; } true. If condition 2 also gets
 else failure, then else part is executed.
 Statement 3;
 Loop control statements
• Loop control statements in Java are used to
 perform looping operations until the given
 condition is true. Control comes out of the
 loop statements once condition becomes false.
• There are 3 types of loop control statements in
 Java language.
 – for
 – while
 – do-while
 Loop
S.no Syntax Description
 Name
 1 for for (exp1; exp2; expr3) Where,
 { exp1 – variable initialization
 statements; ( Example: i=0, j=2, k=3 )
 } exp2 – condition checking
 ( Example: i>5, j<3, k=3 )
 exp3 – increment/decrement
 ( Example: ++i, j–, ++k )
 2 while while (condition) where,
 { condition might be a>5, i<10
 statements;
 }
 3 do while do where,
 { condition might be a>5, i<10
 statements;
 }while (condition);
 switch case statement in Java
Switch case statements are used to execute only specific case
statements based on the switch expression. Below is the syntax
for switch case statement.
switch (expression)
{
 case label1:
 statements;
 break;
 case label2:
 statements;
 break;
 default:
 statements;
 break;
}
 break statement in Java
Break statement is used to terminate the
while loops, switch case loops and for
loops from the subsequent execution.
Syntax:
 break;
Example program for break statement in Java:
 importjava.lang.*; import java.io.*;
class brstmt
{
 public static void main(String args[])
 {
 int i; Output:
 for(i=0;i<10;i++) 01234
 { Coming out of for loop when i = 5
 if(i==5)
 {
 System.out.println(“\nComing out of for loop when i = 5”);
 break;
 }
 System.out.println(““+i);
 }
 }
}
 Continue statement in Java
Continue statement is used to continue the
next iteration of for loop, while loop and do-
while loops. So, the remaining statements are
skipped within the loop for that particular
iteration.
Syntax : continue;
Example program for continue statement in Java:
importjava.lang.*; import java.io.*;
class constmt
{
 public static void main(String args[])
 {
 int i;
 for(i=0;i<10;i++)
 {
 if(i==5 || i==6)
 {
 System.out.println(“\n Skipping from display using continue
 statement \n”+i);
 continue; Output:
 01234
 } Skipping 5 from display using continue statement
 System.out.println(““+i); Skipping 6 from display using continue statement
 } 789
 }
 The return statement in Java
The return statement is used to explicitly
return from a method. That is, it causes
program control to transfer back to the caller
of the method.
 Example program for return statement in Java
class ReturnStatement
 {
 public static void main(String arg[])
 {
 boolean t = true;
 System.out.println("Before the return"); // LINE A
 if(t)
 return; // return to caller
 System.out.println("This won't execute"); // LINE B
 }
 } OUTPUT
 Before the return
 Nested loops in Java
• The placing of one loop inside the body of
 another loop is called nesting. When you
 "nest" two loops, the outer loop takes control
 of the number of complete repetitions of the
 inner loop. While all types of loops may
 be nested, the most commonly nested
 loops are for loops.
OUTPUT
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
 Labeled Loops
• According to nested loop, if we put break
 statement in inner loop, compiler will jump
 out from inner loop and continue the outer
 loop again. What if we need to jump out from
 the outer loop using break statement given
 inside inner loop? The answer is, we should
 define label along with colon(:) sign before
 loop.
Syntax of Labelled loop
 for-each version of the for loop
• It is mainly used to traverse array or collection
 elements. The advantage of for-each loop is
 that it eliminates the possibility of
 programming error and makes the code more
 readable.
• Syntax of for-each loop:
 for(data_type variable : array or collection)
 { }
Example of for-each version of the for loop
class ForEachExample1
{
 public static void main(String args[])
 {
 int arr[]={12,13,14,44};
 Output
 for(int i:arr)
 :
 { 12
 System.out.println(i); 13
 } 14
 } 44
}
 Questions
1. Describe any two relational and any two logical operators in Java with
 simple example.
2. Write general syntax of any two decision making statements and also
 give its examples.
3. Write a program to check whether an entered number is prime or not.
4. Explain break and continue statements with example.
5. State syntax and describe working of ‘for each’ version of for loop with
 one example.
6. Define a class having one 3-digit number as a data member. Initialize
 and display reverse of that number.
7. Explain any four features of Java.
8. Describe ?: (Ternary operator) in Java with suitable example.
9. Explain any two bit-wise operators with example.
10. What is byte code? Explain any two tools available in JDK.
11. What is JVM? What is byte code?
12. ‘?:’ what this operator is called ? Explain with suitable example.
1. Write a program to accept a number as command line argument and print
 the number is even or odd.
2. Define JDK. List the tools available in JDK explain any one in detail.
3. Explain: 1) Platform independence 2) Compiled and interpreted features of
 Java.
4. Write any four mathematical functions used in Java.
5. Write a program to find sum of digits of number.
6. What do mean by typecasting? When it is needed?
7. Write a program to generate Fibonacci series : 1 1 2 3 5 8 13 21 34 55 89.
8. Write a program to print reverse of a number.
9. List eight data types available in java with their storage sizes in bytes.
10. Describe typecasting with one example.
11. What is meant by instance variable and static variable? Describe with
 example.