# comp02 Midterm

Document Sample

```					MIDTERM NOTES
UNARY OPEARTOR

Finally, yYou might need the unary minus operator, which takes the negative of a
number. For example, -X has the same value as (-1)*X. For completeness, Java
also has a unary plus operator, as in +X, even though it doesn't really do
anything.

EG-1 A=5;
B=-A;
EG-2 a=-8;
B=+a;

INCREMENT AND DECREMENT OPERATORS (UNARY OPERATOR)
Increment operator is written by ++.

int count;
Ccount=5;
Ccount++;               // count will now be 6;

Decrement operator --.
–
int count =5;
Ccount--;               //count will now be 4

y = x++;
y = ++x;
System.Oout.println(--x);
z = (++x) * (y--);
Formatted: Font: Bold, Font color: Dark Blue
Pre-Increment(++x) and Post-Increment (x++)

The statement "y = x++;" has the effects of adding 1 to the value of x and, in
addition, assigning some value to y. The value assigned to y is the value of the
expression x++, which is defined to be the old value of x, before the 1 is added.
Thus, if the value of x is 6, the statement "y = x++;" will change the value of x to
7, but it will change the value of y to 6 since the value assigned to y is the old
value of x. On the other hand, the value of ++x is defined to be the new value of
x, after the 1 is added. So if x is 6, then the statement "y = ++x;" changes the
values of both x and y to 7. The decrement operator, --, works in a similar way.

WHAT WILL HAPPEN IF WE WRITE INCREMENT OPERATOR AND
DECREMENT OPERATOR AS FOLLOWS…..
Count=5;                                         count=5;
++count;                                         --count;
Count=5;                       count=5
++count;                       --count

SEE THE FOLLOWING CODE

int n=3;
int m=4;
int r;
r= n* (++m);               // r= n* (m++);
(15)      // result is 15             result is (12)                               Formatted: No bullets or numbering

Assignment plus Operators ( +=, -=, *=, /=, %= )                                   Formatted: Heading 3

The following statements are equivalent.
int x=4;                                          int x=4;
x = x + 3;                                        x += 3;
int a = 7;                                        int a = 7;
a = a – 2 ;                                       a -= 2 ;
int       b = 4;                                  int b = 4;
b = b * 2 ;                                       b *= 2;

Data Type Casting                                                                  Formatted: Font: (Default) Times New
Roman, Font color: Dark Blue
Java supports automatic type conversion if there is no loss of precision. For      Formatted: Heading 3
example:
Formatted: Code
int x;

2
double y;
x = 9;
y = x;        // x (9) is auto converted to double, because no loss of precision
System.out.println(y);    // prints 9.0 on screen

But consider the following code where there is loss of precision. It will not compile
in java.

int x;
double y;
y = 7.5;
x = y;        // loss of precision, Will not compile.
System.out.println(x);

You have to explicitly use a Type Cast operation for this conversion. Like shown
in the example below.

int x;
double y;
y = 7.5;
x = (int) y;        // loss of precision, but forced by programmer to compile
System.out.println(x);    // prints 7 on screen

Type Cast operator is simply the name of the desired data type enclosed in
paraenthesis ( ). It usually appears on the right hand side of an assignment
statement.

int i = 65;                                                                             Formatted: Code
char c;
c = (char) i ;    // cast i to char type
System.out.println(“The Uni-Code Character code 65 is:” + c );

Font color: Dark Blue

// Following code reads a single character from keyboard                      Formatted: Code

System.out.println("Enter any character");
char key;

3
System.out.println("You typed: " + key);                   char ans;
if(ans==’Y’ )
System.out.println(“ I love Dubai”);

For reading String, int or float values we need to use the Scanner class available     Formatted: Font: (Default) Courier New, Font
color: Dark Blue
since Java Version 1.5. For all of the input statements (String, int, float) we need
to include the following line once inside our main method.
Formatted: Code
Scanner sc = new Scanner(System.in);

Then we can read String, int and Float as shown below.

Reading a Sequence of Characters (String)

System.out.println("Type in your name");                                     Formatted: Code

String name;
name = sc.next();

System.out.println("Enter any Integer");                                       Formatted: Code
int number1;
number1 = sc.nextInt();

// Following code reads a Float from the keyboard                              Formatted: Code
System.out.println("Enter any Float");
float fnumb1;
fnumb1 = sc.nextFloat();

Example Program of Input from Keyboard

4
import java.util.Scanner;                                                            Formatted: Code

public class Scan {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int qty;
float price, bill;
String item, name;
System.out.println("Type the item name you bought");
item = sc.next();
System.out.println("Type the price of " + item);
price = sc.nextFloat();
System.out.println("Type how many " + item + " you have
bought");
qty = sc.nextInt();
name = sc.next();
System.out.println(name + ", Your total amount for " +
item);
bill = qty * price;
System.out.println(bill);
}
}

Sample Output/ Input from the above program (Red colored values are sample inputs)
Type the item name you bought                                                        Formatted: Border: Box: (Single solid line,
Auto, 0.5 pt Line width)
Chairs
Formatted: Font: 11 pt, Font color: Dark Blue
Type the price of Chairs
3.1                                                                                  Formatted: Font: 11 pt, Font color: Dark Blue

Type how many Chairs you have bought
3                                                                                    Formatted: Font: 11 pt, Font color: Dark Blue

Smith                                                                                Formatted: Font: 11 pt, Font color: Dark Blue

Smith, Your total amount for Chairs
9.299999

5
THE IF STATEMENT:-                                                          Formatted: Heading 3

Using the If statements we can make decisions.

SYNTAX OF IF STATEMENT

If ( < BOOLEAN EXPRESSION > )                                                     Formatted: Font: Italic, Underline, Font color:
Dark Blue
{
DO THE TASK                                                            Formatted: Font: Italic, Underline, Font color:
Dark Blue
}

Note: Black Underlined words are place-holders. They will be replaced by actual      Formatted: Font: Italic, Underline, Font color:
Dark Blue
values in a real program.

It checks whether the condition is true. If the condition is true it executes the
task. The condition is a Boolean expression.

Egxample:-
int a;                                                                Formatted: Code
a=5;
if( a < 3)
System.out.println(“No is less than three”);   // It will not
// print it because the condition is false.    Formatted: Code, Indent: Left: 2", First line:
0.5"

char ans;
if(ans==’Y’ )
System.out.println(“ I love Dubai”);

IF_ELSE STRUCTURE

Structure

6
Iif( <Boolean condition )>                                                         Formatted: Font: Italic, Underline, Font color:
Dark Blue
{                                                                               Formatted: Font: Not Italic, No underline,
Font color: Dark Blue
Statement-1
Formatted: Font: Italic, Underline, Font color:
}                                                                               Dark Blue

else
{
Statement-2                                                             Formatted: Font: Italic, Underline, Font color:
Dark Blue
}

Here it checks the condition. If the condition is true it will do Statement-1 then
skips Statement-2. If the condition is false, it skips Statement-1 then it will do
Statement-2

EGxample:-
int a;                                                                  Formatted: Code

a=8;
if (a < 5)
{
System.out.println(“hai! hello”);
}
// will print sky is blue     Formatted: Code, Indent: Left: 3.5", First
else                                                                        line: 0.5"
Formatted: Code
{
System.out.println(“sky is blue”);
}

NESTED IF STATEMENT

Iif ( < CONDITION> )                                                        Formatted: Font: Italic, Underline, Font color:
Dark Blue
{                                                                           Formatted: Font: Not Italic, No underline,
Font color: Dark Blue
STATEMENT-1
Formatted: Font: Italic, Underline, Font color:
}                                                                           Dark Blue
Formatted: Font: Italic, Underline, Font color:
else if ( <CONDITION> )                                                     Dark Blue

7
{
STATEMENT-2                                                         Formatted: Font: Italic, Underline, Font color:
Dark Blue
}
else if ( <CONDITION> )                                                    Formatted: Font: Italic, Underline, Font color:
Dark Blue
{
STATEMENT-3                                                         Formatted: Font: Italic, Underline, Font color:
Dark Blue
}
else
{
STATEMENT-4                                                         Formatted: Font: Italic, Underline, Font color:
Dark Blue
}

BOOLEAN EXPRESSIONS

A Boolean expression is an expression which is either true or false.

Math notation          Name                   Java Notation      Java Example
=                  Equal To               ==                 Balance==0
Ans==’y’
/=                 Not Equal To           !=                 Income !=5
>                  Greater than           >                  Expense > income
>                  Greater than     or >=                    Points >=60
equal to

<                      Less than              <                  Pressure < max
<=                     Less than or equal <=                     Expense <=5
to

LOGICAL CONDITION
When I have more than one condition to check I have to connect these two
conditions. These conditions can be connected by using Logical operators.

Logical/Boolean Operators

8
In Java, the boolean operator "and" is represented by &&. The && operator is
used to combine two boolean values. The result is also a boolean value. The
result is true if both of the combined values are true, and the result is false if
either of the combined values is false. For example, "(x == 0) && (y == 0)" is true
if and only if both x is equal to 0 and y is equal to 0.

The boolean operator "or" is represented by ||. (That's supposed to be two of the
vertical line characters, |.) The expression "A || B" is true if either A is true or B is
true, or if both are true. "A || B" is false only if both A and B are false.

The operators && and || are said to be short-circuited versions of the boolean
operators. This means that the second operand of && or || is not necessarily
evaluated. Consider the test

(x != 0) && (y/x > 1)

Suppose that the value of x is in fact zero. In that case, the division y/x is illegal,
since division by zero is not allowed. However, the computer will never perform
the division, since when the computer evaluates (x != 0), it finds that the result is
false, and so it knows that ((x != 0) && anything) has to be false. Therefore, it
doesn't bother to evaluate the second operand, (y/x > 1). The evaluation has
been short-circuited and the division by zero is avoided. Without the short-
circuiting, there would have been a division-by-zero error. (This may seem like a
technicality, and it is. But at times, it will make your programming life a little
easier. To be even more

technical: There are actually non-short-circuited versions of && and ||, which are
written as & and |. Don't use them unless you have a particular reason to do so.)

The boolean operator "not" is a unary operator. In Java, it is indicated by ! and is
written in front of its single operand. For example, if test is a boolean variable,
then

test = ! test;

will reverse the value of test, changing it from true to false, or from false to true.      Formatted: Space Before: Auto, After: Auto
Formatted: Font color: Dark Blue

The Logical Operators are
1.AND ( && )                                                                                Formatted: Font: (Default) Courier New, Font
color: Dark Blue
2.OR ( || )                                                                                 Formatted: Font: (Default) Courier New, Font
color: Dark Blue

AND operator (&&)
9
iIf (( first _Boolean _condition ) && ( second _Boolean_condition ))       Formatted: Emphasis, Underline, Font color:
{                                                                          Dark Blue
Formatted: Underline, Font color: Dark Blue
Statement_Block-_1
Formatted: Emphasis, Font: Not Italic,
}                                                                          Underline, Font color: Dark Blue
Eelse                                                                      Formatted: Underline, Font color: Dark Blue
{                                                                          Formatted: Code
Statement_Block-_2                                                     Formatted: Emphasis, Font: Not Italic,
Underline, Font color: Dark Blue
}
Formatted: Emphasis, Font: Not Italic,
Underline, Font color: Dark Blue
Formatted: Font: Not Italic, Underline, Font
It will do Statement_Block_1-1 only when                                   color: Dark Blue
first condition is true and second condition is false.   Formatted: Emphasis, Font: Not Italic,
Underline, Font color: Dark Blue
Formatted: Underline, Font color: Dark Blue
It will do Statement-2_Block_2 only when                                   Formatted: Emphasis, Font: Not Italic,
Underline, Font color: Dark Blue
first condition is false and second condition is true
Formatted: Underline, Font color: Dark Blue
first condition is false and second condition is false      Formatted: Emphasis, Font: Not Italic,
Underline, Font color: Dark Blue
first condition is true and second condition is false
Formatted: Emphasis, Underline, Font color:
Dark Blue
Formatted: Emphasis, Font: Not Italic,
OR Operator (||)                                                           Underline, Font color: Dark Blue
Formatted: Emphasis, Underline, Font color:
Dark Blue
if (( first _Boolean_ condition ) || ( second_Boolean_ condition ))
Formatted: Code
{
Formatted: Emphasis, Font: Not Italic, Font
Statement-_Block_1                                                  color: Dark Blue

}                                                                          Formatted: Emphasis, Font: Not Italic, Font
color: Dark Blue
else
Formatted: Emphasis, Font: Not Italic, Font
{                                                                          color: Dark Blue

Statement-_Block_2                                                     Formatted: Emphasis, Font color: Dark Blue

}                                                                          Formatted: Emphasis, Font: Not Italic, Font
color: Dark Blue
Formatted: Emphasis, Font color: Dark Blue

It will do Statement-_Block_1 only when
first condition is true and second condition is true.
first condition is false and second condition is true
first condition is true and second condition is false

It will do Statement-_Block_22 only when
first condition is false and second condition is false

10
SWITCH STATEMENT

SEE THE FOLLOWING STATEMENTs:-
int year;                                                    Formatted: Code

year=1;
if(year == 1)
{
System.out.println(“Fresherman”);
}
else if(year==2)
{
System.out.println(“Sophomore”);
}
else if(year==3)
{
System.out.println(“Junior”);
}
else if(year==4)
{
System.out.println(“Senior”);
}
else
{
System.out.println(“Invalid year”);
}

Using switch statement

switch(year)                                                        Formatted: Code

{

case 1:
{
System.out.println(“Fresherman”);
break;

11
}
case 2:
{
System.out.println(“Sophomore”);
break;
}
case 3:
{
System.out.println(“Junior”);
break;
}
case 4:
{
System.out.println(“Senior”);
break;
}
default:
{
System.out.println(“Invalid Year”);
}

Syntax of Switch Statement

switch( Boolean conditionInteger_Type_Expression )    Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
{
Formatted: Code
case value1:                                      Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
{
Statement-1;                      Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
break;
}
case value2:                                      Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
{
Statement-2;                      Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
break;
}
case value3:                                      Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue

12
{
Statement-3;                                                           Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
break;
}
default:
{
Statement-4;                                                           Formatted: Emphasis, Font: 11 pt, Not Italic,
Underline, Font color: Dark Blue
break;
}
}

It first executes evaluates the integer type expressionthe Boolean condition and then it
checks which case matches the value with that expression. It executes that group of
statement under that case. If no match is found then it executes the default case.

See the below program which explains the use of IFSwitch-Case Statement
public class Class1                                                                        Formatted: Code

{
public static void main(String[] args) throws Exception
{                                                                                   Formatted: Code, Indent: First line: 0.5"

int n;                                                                              Formatted: Code

System.out.println(“Enter the no of babies”);

switch(n)
{
case 1:
{
System.out.println(“I have one baby”);
break;
}
case 2:
{
System.out.println(“I have two babyies”);

13
break;
}
case 3:
{
System.out.println(“I have three babyies”);
break;
}
default:
{
System.out.println(“I   have   more   than   twohree
babies”);
}
}

Ternary Operator The (Conditional Operator)

See the below Code
if( n1 > n2)
{
Max= n1;
}
else
{
Max=n2;
}

This can be rewritten using a Conditional operateor

Max =(n1 > n2) ? n1 : n2

Variable=(Boolean condition) ? value1 : value2

It checks the Boolean condition .If the condition is true it puts value1 in the
variable and if the condition is false it puts value2 inside the variable.

14
Rewrite the following if condition using the conditional operator

if( hours work <=40)
{
Pay = hoursworked * payrate;
}
else
{
Pay= hoursworked * 1.5 +payrate;
}

Pay=(hourswork <=40) ? houseworked * payrate : hoursworked * 1.5 +payrate

EXERCISES:

Find the output of the following:-

1. int bal;
bal=80;
if ( bal < 50)
{
System.out.println(“I have a bal less than 50”);
System.out.println(“I need more bal”);
}
else
{
System.out.println(“I have a bal more than 50”);
System.out.println(“ My bal is less”);
}

15
2. int regularpay;
int overpay;
regularpay=890;
overpay=700;
String choice=”first”;
if(choice==”second”)
{
System.out.println(“My choice is chicken pizza”);
}
if(choice==”third”)
{
System.out.println(“My choice is beef pizza”);
}
else
{
System.out.println(“My choice is mutton pizza”);}

3. int p=7;
int a=6;
if (( p < a3 ) && (a >=4))
{
System.out.println(“The nos are less”);
}
else
{
System.out.println(“The nos are big”);
}

4.p=5;
q=9;
16
r =3;
a=( (( p < q) && (q > r)) || ( ( p!=r) )

5. Goal is a variable of type int. Write an If-Else statement the outputs the word
“WOW” if the value of goal is greater than 10 and the word “OH WELL” if the
value is less than 10.

6. There are two variables goal and error of type int. Write an output statement
“WOW” if the value of goal is greater than 10 and value of error is zero.
Otherwise it displays “Oh Well”.

7. Salary and deductions and net are two variables of type double. Give values.
Write an If-Else statement that displays OK and set the value of net to salary
minus deductions if salary is larger than deductions. IF salary is less than
deductions then display the word “Crazy”

8. Suppose speed and visibility are two variables of type int. Write an If-else
statement that sets the variable speed equal to 25 and outputs the word
“Caution”, if the value of speed is greater than 25 and the value of visibility is
less than 20.

9.What is the output?
int time=2; tide=3;
if ( ( time + tide) > 6)
{
System.out.println(“Time and Tide waits for no one”):
}
else
{
System.out.println(“Time and tide wait for me”);
}

10.          int w=1;
int x;
x= (w > 12) ? 5 : 2;

What is the value of x?
17
11. int key;
key=2;
switch (key *2)
{
case                                              1:
{
System.out.println(“Cake”);
break;
}
case 2:
{
System.out.println(“ Ice Cream”);
break;
}
default :
{
break;
}
}
What is the output?
12. What is the value of y?

int x=8;
int y;
Y=( x ==-1)?y :( x ==0)?1 :-1
13. What is the output?
int x=2;
switch(x)
{
case 1:
{
System.out.println(“hai”);

18
}
case 2:
{
System.out.println(“hello”);
}
case 3:
{
System.out.println(“sorry”);
break;
}
default:
{
}}
14. int s=20;
if ( s > 30)
System.out.println(“AAA”);
System.out.println(“BBB”);

What is the output?

15. Using conditional operator write the following:-

Salary = 4x + 100          if x <40
= 300              if x=40
= 4.5 x + 150      if x > 40

16.           int temperature=30;
if (temperature < 50)
System.out.println("It's cold.");
else if (temperature < 80)
System.out.println("It's nice.");
else
System.out.println("It's hot.");
19
1. int x,y,z;
x= 5,y=10,z=13;
if (x < y && x < z) {
if (y < z)
System.out.println( x + " " + y + " " + z );
else
System.out.println( x + " " + z + " " + y );
}
else if (x > y && x > z) {
if (y < z)
System.out.println( y + " " + z + " " + x );
else
System.out.println( z + " " + y + " " + x );
}
else {
if (y < z)
System.out.println( y + " " + x + " " + z);
else
System.out.println( z + " " + x + " " + y);
}
2. int n=2;
switch (n) { // assume N is an integer variable
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
20
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
18. int c=0;
do
{
count++;
}while (count < 0)
System.out.println(“The output after loop finishes is “+count);
19. int count=0;
while (count <5 )
{
System.out.println(count);
Count--;
}
System.out.println(“After Loop”+count);

20.           int n;
for (n=1 ;n <=2;n++)
{

switch (n)
{
case 1:
{
System.out.println(“Cake”);
21
break;
}
case 2:
{
System.out.println (“Ice”);
break;
}
case 3:
{
Break;
}
}

21. Write a java loop statement that displays the word “ I am Happy” 4 times on
the screen.
22 . Write a Java loop statement that prints count.Count begins with 1.It
increments as multiples of 2 and does the loop until count is less than 50

22

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 0 posted: 8/7/2012 language: pages: 22
How are you planning on using Docstoc?