CSC 201-Lecture 3
CSC 201-Lecture 3
Lecture - 3
Agenda
• Review Lecture 2
• Type Casting
• Type Conversion
• Conditionals and Loops
• In-Class Quiz Tuesday : Sep 8th
• Next class : Book assignment will be given
due Tuesday Sep 8th.
Review Of Lecture-2
• Intro to Java.
• Compiling/Executing Java programs
• JDK, JRE, JVM
• Data Types, Variable, constants
• Java program structure
• Type Conversion - Introduction
Errors
Every programming language has some set
of rules to be followed like Grammar in
English.
2 kinds of errors : Compile-time and
Runtime.
Compile-time error : Syntax errors.
Java program structure
Consists of:
Variables
Operators
Expressions, Statements and blocks
Control flow statements
Variables
• What is an identifier/variable?
Rules for writing/creating an identifier.
System.out.println("Enter a integer:");
Scanner myscan = new Scanner(System.in);
int i = myscan.nextInt();
System.out.println("Value of i is : " +i);
}
}
Type Conversion
• What is the importance of a data type?
• Java is a strongly typed language.
• Java is a statically typed language.
• In Java : Explicit type conversion, Explicit cast.
• Difference between Typecast and Type
Conversion?
If you cast a variable into a string you are only
temporarily considering it as a string.
Whereas with conversion you actually change it
permanently.
Default Data type values
• Byte = 0
• Short = 0
• Int = 0
• Long = 0L
• Float = 0.0f
• Double = 0.0d
• Char = '\u0000‘
• String (or any object) = null
• Boolean = false
Type conversion and Typecasting
• Type conversion : Integer.parseInt()
Double.parseDouble()
• Type Casting : Type conversion for
primitive types.
Ex: (int) 2.71 = 2
11 * (int) 0.3 = ?
Java program structure
Consists of:
Variables
Operators
Expressions, Statements and blocks
Decision Making
Control flow statements
Loop statements
Branching statements
Booleans operators
Boolean type has 2 values : True or False
3 important bool operators : &&, ||, !
If we have 2 bool values a, b we can have following values
a && b is T if BOTH operands are T
F if EITHER operand is F
!a is T if a is F
F if a is T
Comparison operators
==, != , <, <=, >, >=
These operators are defined for each primitive type and produce a boolean
result.
Ex : Results for below?
2 == 2
2 == 3
2 != 3
2 != 2
2<3
2>3
2 <= 3
2 >= 3
If a and b are T, F
13) Calculate (!(a && b) && (a || b))
14) Calculate ((a && b) || !(a || b))
Control Flow Statements
Decision making statements : If, If-else,
switch
IF STATEMENT: If different action is to be
performed on different inputs, we use IF
statement. It is basically a decision making
statement. Its construct is :
Form-1
If (<boolean expression>)
{ <statements> }
Form – 2 : if-else
If – else statement
if(<boolean-expression>)
{ <statement-1> ; }
else(<boolean-expression>)
{ <statement-2>; }
• Form-3 : Nested – If’s
if(<boolean-expression>)
<statement-1>;
else
if(<boolean-expression>) { <statement-2>; }
else
if(<boolean-expression>) { <statement-3>; }
…..
Example – If else
Class test
{
Public static void main(String[] args)
{
int x = 2;
if(x < 5)
{
System.out.println(“ Number is less than 5.”);
}
else
System.out.println(“Number is greater than or equal to 5.”);
}
}
Nested If-else
int score;
char grade;
Scanner scan = new Scanner(System.in);
score = scan.netInt();
if(score >= 80)
More than one statement
grade = ‘A’;
is satisfied here!
else But once a condn is satisfied,
if(score >= 70) Remaining are not evaluated.
grade = ‘B’;
else
if(score >= 60)
grade = ‘C’
System.out.println(“Grade is :” +grade); o/p : Correct
int score;
char grade;
Scanner scan = new Scanner(System.in);
score = scan.nextInt();
if(score >= 80)
grade = ‘A’;
else
if(score >= 70)
Remove!
grade = ‘B’;
else
if(score >= 60)
grade = ‘C’
System.out.println(“Grade is :” +grade); O/P = ?
Switch statement
• It is a shortcut to certain form of if-
statement. If we have a stack of if
statements, Java has a shorthand i.e
switch-case statements.
if (x == 0) dosomething();
else if (x == 1) dosomethingelse();
else if(x == 2) dosomethingelse();
…..
Syntax for switch statement
Switch (x) //x must be variable/expression
{
Case 0: dosomething(); break;
Case 1: dosomethingelse(); break;
Case 2: dosomethingelse(); break;
..
Case n: dosomethingelse(); break;
Default : dosomethingelse();
}
switch(x) : x must be a variable or an expression that can
be cast to an int without loss of precision.
Syntax
while ( <boolean expression> )
{ <statements> }
The statements get executed until the
boolean expression evaluates to False.
While loop example
int a = 0;
while( a <= 10 )
{
System.out.println( a );
a = a + 1; /* a++? */
}
What is the output here?
Example
Class whiledemo
{
public static void main(String[] args)
{
int count = 1;
while(count < 11)
{
System.out.println(“Count is :” + count);
count++;
}
}
}
Do-While Loop
• Do-while statement: Same as While statement. The
expression is evaluated at the bottom instead of top. So,
loop will run atleast once.
int count = 1;
do
{
System.out.println(“Count is:” + count);
count++;
}while(count < 11);
}
For Loop
If you want to initialize one or more variables
and may want to increment one or more
variable. The loop is repeatedly executed until a
particular condition is satisfied.
Syntax:
For (initialization ; boolean-exp ; increment)
{
set of statements If the expression evaluates to
} false., the loop is
terminated
Example
Class for_demo
{
public static void main(String[] args)
{ Invoked after each
for(int I = 1; I < 11; i++) Iteration of the loop!
{
System.out.println(“Count is :” +i);
}
}
}
How to create an infinite loop with for?
Branching Statements
• Break statement : If in some scenario you
want to exit the loop without completing
the rest of the execution of statements
Break was used in our switch statement.
• Continue statement : A continue statement
returns to the beginning of the innermost
enclosing loop w/o completing the rest of
the statements of the loop.
Continue statement example
Public static void main(String[] args)
{
int num;
for(num = 1; num < 15; num++)
{
if(num >= 9)
{ System.out.println(“The number” +num+ is greater than or
equal to 9!”);}
else
continue;
System.out.println(“This statement executes:”);
}
}//what is the output here?
Infinite Loops
What is an infinite loop?
while(true)
{ <statements> }
for(; ; )
{} //infinite loop
May be used in embedded control code which some may be designed
to run forever.
Sometimes used, when you don’t know the exact condition under which
you want to use a while, but you can break the loop by using break
as of its statements in the body.
Program to check if a number is
prime or not
public static void main(String[] args)
{
int num_to_check, mod, I;
System.out.println(“Enter a number to check if it is prime or not:”);
//check using scanner class
for(I = 2; i< num_to_check ; i++)
{
mod = num_to_check % i;
if(mod == 0)
{
System.out.println(“Not a prime number”);
break;
}
}
if(I == num_to_check)
System.out.println(“Prime Number!”);
}
Announcements
• Homework 1 is due Thursday. It is posted
on my blog.
• There will an In-class quiz on Tuesday
Sep8th 2009.
• The prime number example will be posted
with comments.
• Next lab session.
• Exam timings : 12:15 – 12:45
Homework output sample run
A random number generated is : 2
Enter the limit for printing even numbers : 5
The number 1 is not an even number
The number 2 is an even nummber
The number 2 matches the random number 2
The number 3 is not an even number
The number 4 is an even number
The number 5 is not an even number