P in JAVA M2
P in JAVA M2
Programming in Java
Course Code 21CS652 CIE Marks 50
Teaching Hours/Week (L: T: P: S) (3:0:0:0) SEE Marks 50
Total Hours of Pedagogy 40 hours Theory Total Marks 100
Credits 03 Exam Hours 03
Course Learning Objectives
CLO 1. Learn fundamental features of object-oriented language and JAVA.
CLO 2. To create, debug and run simple Java programs.
CLO 3. Learn object-oriented concepts using programming examples.
CLO 4. Study the concepts of importing packages and exception handling mechanism.
CLO 5. Discuss the String Handling examples with Object Oriented concepts.
Teaching-Learning Process (General Instructions)
These are sample Strategies, which teachers can use to accelerate the attainment of the various course outcomes.
1. Lecturer method (L) need not to be only a traditional lecture method, but alternative effective teaching methods could be
adopted to attain the outcomes.
2. Use of Video/Animation to explain functioning of various concepts.
3. Encourage collaborative (Group Learning) Learning in the class.
4. Ask at least three HOT (Higher order Thinking) questions in the class, which promotes critical thinking.
5. Adopt Problem Based Learning (PBL), which fosters students’ Analytical skills, develop design thinking skills such as the ability
to design, evaluate, generalize, and analyze information rather than simply recall it.
6. Introduce Topics in manifold representations.
7. Show the different ways to solve the same problem with different circuits/logic and encourage the students to come up with their
own creative ways to solve them.
8. Discuss how every concept can be applied to the real world - and when that's possible, it helps improve the students'
understanding.
Module-2:
Operators: Arithmetic Operators, The Bitwise Operators, Relational Operators, Boolean Logical operators, The Assignment
Operator, The ? Operator, Operator Precedence, Using Parentheses,
Control Statements: Java’s Selection Statements, Iteration Statements, Jump Statements.
Textbook 1:Ch 4,Ch 5.
Teaching-Learning Process Chalk and Talk, PowerPoint Presentation RBT Level: L1, L2,
Textbooks
1. Herbert Schildt, Java The Complete Reference, 7th Edition, Tata McGraw Hill, 2007. (Chapters 2, 3, 4, 5, 6,7, 8, 9,10, 12,15)
Reference Books:
1. Mahesh Bhave and Sunil Patekar, "Programming with Java", First Edition, Pearson
Education,2008, ISBN:9788131720806.
2. Rajkumar Buyya,SThamarasiselvi, xingchen chu, Object oriented Programming with java, Tata
McGraw Hill education private limited.
3. E Balagurusamy, Programming with Java A primer, Tata McGraw Hill companies.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators. Assume integer variable A holds 10 and
variable B holds 20, then:
Operator Description Example
+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left operand by right operand and returns remainder
B % A will give 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19
Example: The following simple example program demonstrates the arithmetic operators. Copy and
paste the following Java program into Test.java file and compile and run this program:
Example: The following simple example program demonstrates the relational operators. Copy and
paste the following Java program in Test.java file and compile and run this program. :
& Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12 which is 0000 1100
both operands.
| Binary OR Operator copies a bit if it exists in either operand. (A | B) will give 61 which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) will give 49 which is 0011 0001
but not both.
~ Binary Ones Complement Operator is unary and has the effect (~A ) will give -61 which is 1100 0011
of 'flipping' bits. in 2's complement form due to a
signed binary number.
<< Binary Left Shift Operator. The left operands value is moved A << 2 will give 240
left by the number of bits specified by the right operand. which is 1111 0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15
right by the number of bits specified by the right operand. which is 1111
>>> Shift right zero fill operator. The left operands value is A >>>2 will give 15
moved right by the number of bits specified by the right which is 0000 1111
operand and shifted values are filled up with zeros.
Logical Operators
The following table lists the logical operators. Assume Boolean variables A holds true and variable B
holds false, then:
Operator Description Example
Called Logical AND operator. If both the operands are non-zero, then the
&& condition becomes true. (A && B) is false.
Called Logical OR Operator. If any of the two operands are non-zero, then the
|| condition becomes true. (A || B) is true.
Called Logical NOT Operator. Use to reverses the logical state of its operand.
! If a condition is true then Logical NOT operator will make false. !(A && B) is true.
The following simple example program demonstrates the logical operators. Copy and paste the following
Java program in Test.java file and compile and run this program:
public class Test {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Miscellaneous Operators
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should
be assigned to the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
public class Test {
public static void main(String args[]){ int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
// This would produce the following result:
// Value of b is : 30 Value of b is : 20
instanceOf Operator
If the object referred by the variable on the left side of the operator passes the IS‐A check for the
Operator Precedence
Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>> = <<= &= ^= |= Right to left
Comma , Left to right
There may be a situation when we need to execute a block of code several number of times, and is
often referred to as a loop. Java has very flexible three looping mechanisms. You can use one of the
following three loops:
• while Loop
• do...while Loop
• for Loop
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays and we will not
explain it.
while Loop
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true, then the actions inside the loop will be
executed. This will continue as long as the expression result is true.
Here, key point of the while loop is that the loop might not ever run. When the expression is tested
and the result is false, the loop body will be skipped and the first statement after the while loop will
be executed.
public class Test {
public static void main(String args[]) { int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x ); x++;
System.out.print("\n");
}
}
}
do..while Loop
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least
one time.
The syntax of a do...while loop is:
do
{
//Statements
} while(Boolean_expression);
Notice that the Boolean_ expression appears at the end of the loop, so the statements in the loop executes
once before the Boolean is tested. If the Boolean expression is true, the flow of control jumps back up to
do, and the statements in the loop execute again. This process repeats until the Boolean expression is
false.
for Loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a
specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
The syntax of a for loop is:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a
switch statement.
The break keyword will stop the execution of the innermost loop and start executing the next line of code
after the block.
The continue keyword can be used in any of the loop control structures. It causes the loop to immediately
jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of control to
immediately jump to the update statement. In a while loop or do/while loop, flow of control immediately
jumps to the Boolean expression.
The syntax of a continue is a single statement inside any loop:
continue;
Example:
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x ); System.out.print("\n");
}
}
}
There are two types of decision making statements in Java. They are:
• if statements
• switch statements
The i f S t a t e m e n t :
The if Statement: An if statement consists of a Boolean expression followed by one or more
statements.
The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Example:
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
// This would produce the following result: This is if statement
The i f … e l s e i f … e l s e S t a t e m e n t :
An if statement can be followed by an optional else if...else statement, which is very useful to test
various conditions using single if...else if statement.
• When using if , else if , else statements there are few points to keep in mind:
• An if can have zero or one else's and it must come after any else if's.
• An if can have zero to many else if's and they must come before the else.
• Once an else if succeeds, none of the remaining else if's or else's will be tested.
The syntax of an if...else is:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
The N e s t e d i f … e l s e S t a t e m e n t :
It is always legal to nest if‐else statements which means you can use one if or else if statement inside
another if or else if statement.
The syntax for a nested if...else is as follows:
if(Boolean_expression 1)
{
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
public class Test {
public static void main(String args[]){
int x = 30;
int y = 10;
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
// This would produce the following result:
// X = 30 and Y = 10
Example:
public class Test {
public static void main(String args[]){ char grade = 'C';
switch(grade){
case 'A' : System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
break;
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
// This would produce the following
// Well done Your grade is a C
“Determine the season based on the given month value. Provide a detailed explanation of how the code
works and what output it produces for the month of April."
// Demonstrate if-else-if statements.
class test {
public static void main(String args[]) {
int month = 4; // April
String season;
if (month == 12 || month == 1 || month == 2)
season = "Winter";
else if (month == 3 || month == 4 || month == 5)
season = "Spring";
else if (month == 6 || month == 7 || month == 8)
season = "Summer";
else if (month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
Here is the output produced by the program:
April is in the Spring.
class test {
public static void main(String args[]) {
outer: for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}