0% found this document useful (0 votes)
21 views

Java Practice

Uploaded by

kulasmart100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Practice

Uploaded by

kulasmart100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

asfirst

class. less than 60but mu


as third class and
Java Programming 60is declared Wess
48 morethan than 40is declared
than 80
but
less but more 50
statement
is
distinction, less than if-else
as class,
80isdeclared assecond The format of nested
than
50is declared
asunsuccessful.
40 isdeclared Expression-1)
if (Boolean

Block 1

els
Expression-2)
(Boolean
else if

Block 2
Expression-3)
else if (Boolean

Block3

Expression-n)
else if (Boolean

Block n

else

Block for other Alternatives


is excu
and if it true then Blockl Block
Th

show Boolean Expression


the first then gr
if-else statements is true
The nested
if with Boolean
Expression-2 and ifit true,Bl ag
forthe else andifitis
If it fails, the prograrn checks

forthe else if
with Boolean Expression-3 and it F
executed. Ifit fails, the program checks else
if statement.The
final 1S Ooptional
les
till the last else
statemë

3 is executed. The
checking continues The nested if-else se
not met by the earlier alternatives. classifica
will take care of conditions marks
províded ít students
the entire structure. Program 3.4illustrates
will execute only one block of st

th
Output 3.4
Program 3.4
Run-1 Name
inport java.util.Scanner; Enter Student
publiC class NestedIf ( Daniel Marks

by reading Enter Student


Progran
the use of Nested If statement
to i,1lustrate 92
St

them asdistinction,
the marks of the student and classifying
=Daniel 1
Name
Student
and unsuccessful.

(
=92
first, second, third class Marks
Student
=DISTINCTI
main(String[] args) Secured
publiC static void
String name;
nt narki Run-2 Name

Scanner inp= new Scanner (System. in); Enter Student


System.out.println("Enter Student Name \n"); Anburaj
Control Statements 49

name inp.nextLine ();


=
Enter Student Marks
System. out.println ("Enter Student Marks");
67
mark = inp nextInt ():
Student Name =Anburaj
if(marks=80)
Student Marks =67
Secured =FIRST CLASS
System, out-print ln("Student Name +name);"
System. out.prìntln("Student Mark =+mark);
Run-3
System. out.println("Secured DISTINCTION");
Enter Student Name
Poovarasan
else if (mark=60)
Enter Student Marks
54
System.out println("Studernt Name "+name) ; Student Name -Poovarasan
System.out.println("Student Mark ="+mark); Student Marks =54
System.out.println (" Secured =FIRST CLASS");
Secured =SECOND CLASS
3
else if (mark >= 50)
Run-4
Enter Student Name
System. out.println("Student Name ="+name)
Ramkumar
System.out.println ("StudentMarks ="+mark);
Enter Student Marks
System.out.println ("Secured =SECOND CLASS" ):
47
Student Name =Ramkumar
else if (mark > 40) Student Marks =47
Secured =THIRD CLASS
System. out.println(MStudent Name ="+name);
System.out.println ("Student Marks ="+mark); Run-5
System.out.println ("Secured -THIRD CLASS");
Enter Student Name
Ramya
else if (mark < 40) Enter Student Marks
34
System.out.println ("Student Name ="+name) i
System.out.príntln("Student Marks ="mark)
UNSUCCESSFUL
; Student
");
Name =Ramya
Student Marks =34
System.out.println(" Secured Secured =UNSUCCESSEFUL
Program 3.5

inport java.util.scanner;

public class LogicalOp (


The program illustrates the use of Logical Operator by
*reading the experience and salary and calculates the new salary

publiC static void main (String [


J args) {
String empnamei
int exp;
float salary.

Scanner inp- new Scanner (SyStem.in);


System. out.println("Enter Employee Name ): "
ernpnane inp.nextLine( ):
Systen.out.println("Enter Employee Experience ")
exp = inp.extInt ();
Systen. out.println ("Enter Employee
salary
Salary ")
inp,nextFloat ()

it{(ezp=15)&e salary >=8000))

System. out.println ("Employee Name "tempname )


Control Statements 51

System. out.println("Experience =+exp);


System.out.println("Salary (salary+1500)
):
else

if((exp<15) && (salary 6000))

System out.println("Employee Name "+empname)


System.out.println("Experience ="+exp);
System.out.println("Salary

The program reads name, experience and salary of the employee using scannerclass. If tests whether the
experience i greater than 15 and the salary is greaterthan Rs. 8000.If so,the salary
is increased by Rs. 1500.
Ifthe first conditional statement the control flows
fails to the second ifstatement which checks whether it is
less than 15 and the salary is greater than Rs. 6000 and if so the salary is
improved by Rs. 1000. The output
of Program 3.5 is the same as Program 3.3. So far these sections have
compared numerical values with
various formats of if statements. The next section checks
whether the String objects are equal or not.

3.6 COMPARING STRING OBJECTS


String objects introduced in Chapter 2
are compared here with two methods;the remaining
methodsare
discussed in Chapter 7. Two Strings are compared to see
whether they are equal or not. The two meth
ods are equals ()and compareTo methods. The equals () method comparestwo strings by
checking
whether they contains equal number of characters, the same
characters, in the same order and the same
case, if so,they areequal. Program 3.6 explains the use of
equals()method.

Program 3.6
import java.util.Scanner;
Output 3.6
public class Equals{
Enter First String
The program demonstrates the use of equals () Raguram
*
methods
*by comparing two strings Enter Second string
RAGURAM
publiC Enter Third String
static void main (String U args)(
String s1, s2, s3; Raguram
First String =Raguram
Scanner inp= new Scanner(System in) Second Strìng -RAGURAM
Third String -Raguram
Systet,out.println("EnterFirst string "):
Raguram and RAGURAM are
S1 inp,nextiine();
System,out.printn("Enter Second String") EQUAL= false
s2 inp nextLine() Raguram and Raguram are
System, outprintln(Enter Third String,") EQUALtrue
s3 inp.nextLine () i
RAGURAM and Raguram are
EQUALafalse
System.out.printin("PírstString s1)
System.out.println("SecondString 2)
52 Java Programming

System, out.println(Third string +S3):

System,out.println (sl + " and" +s2 +" are EQUAL=+s1.equals(


and +83 +* are EQUAL,=
s(s2)):
System,out.println (s1 +
System. out.println(s2 + and M+s1.equals
" +s3t are EQUAL="+s2.eguals(s3) );
(s31.

The first string si and second string s2 are cqual if the


case is ignored, but
equals() methods has returned False. they are not
The first string and third
s1 equal so
string s3 are equal
method has returned True. The second string s2 and third sothe
has returned False. string s3 are not equal sothe equals
equals ()meth
Another approach is to use the CompareTo (0 method
which returns
ments. If the strings are equal, three values based
CompareTo)
returns zeroifthe first on
theargy
string as per the alphabetical order it returns a string is greater than
value greater than the secom
the second string as zero and if the
per the alphabetical first string
order it return a is less tha
the use of CompareTo () value less than zero.
method Program 3.7 deserik

Program 3.7

import Output 3.7


java.util.Scanner;

Enter First String


public class
1** Compare ( java
* The program Enter Second string
methoãs demonstrates the use of pascal
compareTo
by comparing Enter Third string
two strings
fortran
public static void ain(Stringl) First String
String s1, s2, args) =java
s3; Second String
-pascal
Scanner Third String
inp new Scanner(System. =fortran
System, in) ;
s1 = out.println("Enter First String "); java and java are
inp,nextLine(): pascal
EQUAL
Systen, out.println and fortran are No
("Enter Second String "): EQUAL
82 = i
np,nextLíne (); java and java=0
Syste.out.println
S3= inp. nextLine():("Enter Third String "); java and
fortran=4
fortran and
pascal=-10
ZERO BOTH
Systen,
out.println ("First STRINGS ARE
String EQUALS
System, "+s1):
outprintln("Second
SysteO,Outprintln("Third String "+s2): GREATER THAN ZERO FIRST
String STRING
+S3): IS GREATER THAN
f
(s1.conpaeTo(s1) SECOND STRING
0)
Syster, LESS THAN ZERO
out.,println(s1 and
FIRST
else +s1 + are STRING IS LESS mHAN
EQUAL")): SECON
Eysten,out STRING
println (s1 + and "+s1 +M are NOT
if (s2.conpar EQUAL"):
eTo(#3)0)
SYstem, out.println
(s2 +M
else
and"3+* are EQUAL): A
System.
out.println a
System.
System.out.println(s1+*
(s2
+and"3
and
+ are NOT
EQUAL");
out.println (s1+*
and "*s1+"="+sl.compare'To (s1))
re
Systen.out.print ln (s3+"
and "*s3+"*"*81.compareTo (s3))
"*s24ts3.conpareTo (s2) )
Control Staternents 53

System. out.println( "ZERO B0TH STRINGS ARE EOUALS "):


System.outprintln ( "GREATER THAN ZERO FIRST STRING IS GREATER THAN SEcOND
STRING");
Svstem. out.println ("LESS THAN ZERO FIRST STRING IS LESS THAN SECOND STRING"):
}}

The program received three stringsand to prove the equalityof strings the string s1 is compared with
string s1 and they are equal so the result is equal to 0 and the message
displayed is EQUAL. The string
s2 iS compared with string s3; since they are different, the message displayed is NOT EQUAL. To display
thecompared results the strings s1 and s1 are compared and the outcome is 0. The strings s1 and s3

are compared in the alphabeticalorder. The distance betweenjava and fortran is 4 which is greater than
zero.The stringss2 and s3 are compared in the alphabeticalorder and the distance between fortranand
pascal is -10, which is less than zero. The conditional statements covered so far have another version
if

the true part orthe false part has only one statement, as explained in the following section.

3.7 THECONDITIONAL OPERATOR


A oneline code that works like an if-else statement called a conditionaloperator or ternary operator.
is

It can assign value to a right hand side variable based on an expression'sBoolean value. The general
format of the ternary operator is

result = testCondition ? valuelvalue2;

f the test condition is true, assign the value of value1 to result; otherwise, assign the value of value2
to result. In Program 3.3, if the salary of an employee is greaterthan Rs.8000, his increment Rs.1500
else Rs.1000 if theexperience is ignored. This can be expressed as
increraent = salary>8000 ? 1500 1000;
salary #salary +increment;

Ifthe salary ís greater than Rs. 8000 the outcome of the Boolean expression is true and Rs.I 500 is
assigned to the variable increment;otherwise Rs. 1000 is assigned. The example has used the Boolean
expression in the conditional operator. Boolean state can also be used in place of the Boolean expres

Sion. Apartfrom using a ternary operator to assign values to a variable, it can be used as follows

String s markl > 40 ? "Pass Fail"

Ifmarki is greater than or equal to 40 "Pass" is assigned to string s;otherwise "Fail'" is assigned. The
same example can be used inside a display statement also.

System, out.println(mark1 40 "Pass" "Pail):

The line of code will display either Pass or Failbased on the value of markl. A better way to handle
multiple if-else statements is provided in the next section.
Program 3.8
import java.util.Scanner

public class Markswitch{

The program demonstrates the use of Switch statement


* by getting the grades of the student

publiC static void main(Stringl] args)


String name;
char grade;

Scanner inp= new Scanner (System. in)


System. out.println("Enter Student Name ")
name = inp.nextLine()
System.out.println ("Enter a character: ")
grade = inp, next ().charAt(0)
System.out.println ("sTUDENT NAME"+name) ;
System.out.print ("GRADE -"):
Switch (grade)

case D':

System.out.println("DISTINCTION
break;
):
caseF
Output 3.8
System.out.println("FIRST ): Run-1
break;
Enter Student Name
case S: S Maheswari
Enter a character:
Systen,out.println ("SECOND ") D
break; STUDENT NAME Maheswari
GRADE DISTINCTION
Case T

Run-2
System,out.println (
"THIRD "): Enter Student Name
break;
Ruban
Enter a character:
default :

Systen.out.println(FAIL
break;
) X
STUDENT NAME
GRADE
Ruban
=FAIL

You might also like