Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Ch Java

Unit 3 covers the fundamentals of Java programming, including the role of compilers, the Java Virtual Machine (JVM), and the structure of Java programs. It explains key concepts such as variables, data types, control statements, methods, classes, and exception handling, emphasizing Java's object-oriented nature and portability. Additionally, it discusses the use of Integrated Development Environments (IDEs) and provides examples of common programming errors and their corrections.

Uploaded by

Palak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Ch Java

Unit 3 covers the fundamentals of Java programming, including the role of compilers, the Java Virtual Machine (JVM), and the structure of Java programs. It explains key concepts such as variables, data types, control statements, methods, classes, and exception handling, emphasizing Java's object-oriented nature and portability. Additionally, it discusses the use of Integrated Development Environments (IDEs) and provides examples of common programming errors and their corrections.

Uploaded by

Palak
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

unit 3 Fundamentals of Java Programming

• A computer program is a sequence of instructions given to the computer in order


to accomplish a specific task
• A compiler translate high level program code into machine language code.
to
• Java is a very popular high level programming language and has been used widely
create various types of computer applications such as database applications, desktop
applications_,Web based applications, mobile applications, and games.
• A Java compiler tra.nslates high level language into Java Bytecode.
• Byte code is set of instructions or Java class file.
• A Java interpreter, called the Java Virtual Machine (JVM), translates
the bytecode into machine code and then executes it.
a
• Bytecode can be run on any platform (say Windows, Linux, or Mac) as long as it has
JVM running on it. This makes the Java programs platform independent and highly
portable.
• To write a Java program, you will need a Text Editor (for writing the code)and a Java
compiler (for compiling the code into bytecode ).
and a
• Java Integrated Development Environments (IDEs) are equipped with a text editor
Java compiler thus simplifying writing, compiling and executing Java programs.
s .\
• Java Net Beans IDE is freely downloadable open source for writing Java program
• Comments are used for enhancing the readability of code and are ignored by the
compiler when compiling a file.
o single line comments by Beginning a comment line with two consecutive
forward
slashes (//)
o multiple line comments by Writing the commr:nt between the symbo ls/* and*/

be
• A packag e in java is a group of related classes. However the packag e name can
the
different from either the class or the source file name. NetBeans, by default, names
package with the same name as the project, except that it is in all lower case.
• The contents of a class are enclosed within curly braces.
body is
• A method is a group of statements written to perform a specific task. The method
will
enclosed within a pair of curly braces and contains the statements that the method
execute.
run a
• ~ Main is a special method that every Java application must have. When you
program, the statements in the main method are the first to be execute d.
• All Java stateme nts must end with a semicolon.
your
· • NetBea ns has a default Compil e on Save feature, you do not have to compile
program manually, it is compile d automa tically when you save it.
program
• Variables are used to store the program data.It can change its value during
er's
execution. Technically, a variable is the name for a storage location in the comput
internal memory. The value of the variable is the content s at that location.
used.
• All data variable s in Java have to be declare d and initialized before they are
that the
• When declarin g variables, we have to specify the data type of information
member will hold - integer,byte,short, float, double,char,boolean. The type of a variable
tells the compiler, how much memory to reserve when storing a variable of that type.
• Variable names can begin with either an alphabetic character, an underscore
LJ, or a dollar sign($) or a letter. They can consist of only alphabets, digits, and
underscore.Spaces are not allowed in variable names.Underscores are allowed.
Reserved words in Java cannot be used.Java is a case-sensitive language.
• Operators are special symbols in a programming language and perform certain specific
operations.
• Java provides two statements - the if else statement and the switch statement for
executing a block of code conditionally.
• The if statement in Java lets us·execute a block of cod,e depending upon whether an
expression evaluates to true or false.
• Within the switch statement, there can be many case statements.The expression is
compared with the constants in each case group and the matching case group is
executed. The expression in the switch statement must evaluate to byte, short, int, or
· char. The break causes the switch to terminate.
• The ability of a computer to perform the same set of actions again and again is called
looping. The sequence of statements that is repeated again and again is called the body
of the loop. The test conditions that determine whether a loop is entered or exited. A
single pass through the loop is called an iteration.
• Java provides three statements - the while statement, the do while statement, and
the for statement for looping.
• The while statement evaluates the test before executing the body of a loop.
• The do while statement evaluates the test after executing the body of a loop.
• The for loop evaluates the test condition before executing the loop. The initial_value
initializes the value of the loop counter.The test_condition tests whether the loop should
be executed again. The loop is exited when the test condition fails.The step updates the
counter in each loop iteration.
• The loop given above counts up the loop index. It is an incrementing loop. We can also
count down in a loop for a decrementing loop.
• Arrays are variables that can hold more than one value, they can hold a list of values of
the same type.The array index goes from Oto n-1 for an array of size n.
• Length property gives the size of the array.
• A method in Java is a block of statements grouped together to perform a specific task. A
method has a name, a return type, an optional list of parameters, and a body.
• The method name has parameter list within the round brackets that allows data to be
passed into the method. The method body contains the statements of the method. The
statements end with an optional return statement that returns a value back to the calling
method. The return type is the type of the value that the method returns.
• The static modifier allows us to call the method without an invoking object.
• Java is an Object Oriented Programming (OOP) language. In an OOP language, a
program is collection of objects. Each object is an instance of a class.
• A class is a physical or logical entity that has certain attributes.A class is a template
from which objects are created. All objects of the same class have the same type of data
members.
the
• The data members of a class are like global variables - they can be accessed by all
method members of the class.
• Method members of a class are invoked on an object to perform the action associated
with that method.Method members can get, set or update the class data members.
• Data members and method members of an object are accessed using the dot
(. )operator
• A special method member called the constructor method is used to initialize the data
members of the class.The constructor has the same name as the class, has no return
is
type, and may or may not have a parameter list. Whenever a new object of a class
created, the constructor of the class is invoked automatically.
• Private members of a class cannot be accessed outside the class. They are visible
inside the class.
• A getter method returns the value of a data member.
• To use a prebuilt class and associated methods in those class.use the keyword import.
il
• To take user input we use the prebuilt Scanner class which is available in the java.ut
package.
• parselnt() that takes a String as parameter and returns the equivalent integer.
• Integer class is in the java.lang package.
• sort()method to arrange an array of integers in ascending order.
• binarySearch() method helps us search for a specific element in the array.
ase
• String class methods like charAt, concat, contains, endsWith,equals ,equals lgnoreC
ng
,indexOf, isEmpty,length ,replace ,tolowe rCase ,toUpperCase are available in java.la
package.
te
• An error situation that is unexpected in the program execution and causes it to termina
unexpectedly is called an exception.
• Java handles exceptions by
try-A try block surrounds the part of the code that can generate exception(s).
catch -The catch blocks follow a try block. A catch block contains the exception.
handle r - specifi c code that is executed when the exception occurs.
ing
• An assertion is a useful mecha nism for effectively identifying/detecting and correct
logical errors in a program.
that
• A multithreaded progra m is one that can perform multiple tasks concur rently so
created in
• there is optimal utilization of the compu ter's resour ces.In Java, thread s can be
two ways
1. By. extend ing the Thread class
2. By implem enting the Runna ble interfac e
The
• Chang e priority level of thread using the setPrio rity() method of the Thread class.
Priority levels can range from 1 to 10.
numbe r of
• The sleep() method causes the thread to suspen d execut ion by the specifi ed
millise conds parameter.
• A thread can enter a wait state by invokin g the wait() method .
reference. These classes wrap
• Wrapper class is used to pass the primitive data types by
wrapper classes are Boole an
the primitive data type into an object of that class . Some
Byte,Character, Integer, Float, Double ,Long ,Short.

Errors
s true.
• Run time errors occur when the test condition is alway
ition in a do-while
• Do not forget the semi colon at the end of the test cond
loop.
ition in a while loop.
• Do not place a semi colon at the end of the test cond
the set of curly brace s
• If there is only one statement in the body of the loop,
enclosing the body can be omitted.
updation part of the loop
• You can use multiple items in the initialization and the
by separating them with the comma operator.
the loop, it will make it
• Do reme mber to use indentation to align the body of
easie r for you to debu g your code.
• Placing a semi colon at the end of a for statement.
of the loop. It is not visibl e
• The scop e of the variable count is only within the body
outsi de the loop.
array index more than array
• An Array index out of bounds error occurs when you give
size.
• Array must be sorte d before invoking binarySearch() .

MCQ
statement
1.lf x = 20, y = 10, what will be the value of x, if we write the
x+= y?
(a) 30
(b) 20
(c) 10
(d) 21
Ans a

2. Which of these is an incorrect statement ?


(a) It is necessary to use new operator to initialize an array.
s surrounded by curly braces.
(b) Array can be initialized using comma separated expression
(c) Array can be initialized when it is declared.
(d) None of the above

Ans a .

3. What is the output of relational operators ? 1


(a) Integer
(b) Boolean
(c) Characters
(d) Double
I
Ans b

4. A group of statements which get executed based on a condition is called


(a) Selection
(b) Sequential
(c) Iteration
(d) None of these

Ans a

5.Predict the output of the following expression of the initial value of x is 5.


x=((++x)*2)+7 (cbse)
a. 19 ··
b. 21
C. 18
d.20
Ans a.

6. With x = 0, which of the following are legal lines of Java code for changing the
value of x to 1 ?
1. X ++;
2. X = X + 1;
3. X += 1;
4. X =+ 1;
(a) 1, 2 & 3
(b) 1 & 4
(c) 1, 2, 3 & 4
(d) 3 & 2

Ans a

7. Which of these operators can be used to concatenate two or more String objects ?
(a)+
(b) +=
(c) &
(d) 11

Ans a

8. Which of these is an incorrect array declaration ?


(a) int arr[] = new int[S]
(b) int Darr = new int[S]
(c) int arr□
arr = new int[5]
(d) int arr[] = int [5] new

Ansd
I 9· fdontWy tho type ct operator used
ff CA =-8)
(J) Alftftmetc
(0) RefaticnaJ
(IU} Lcgkal
(Iv) Auignment

AN O

10. _ _ _ _ _ Is a special method that every Java application must ha,te.


a, Getter
b. s.tter
c.Mafn
d. Default

Ana Maln

nn fn lhe blanks
1.methods dedared In a class ato called morntmc rno:inma
2.0bfflct is en lnllance ot a dass.
3.Jayn Ytaupr Mocb•rm ltwla1u lho t>ytococto into mncntno codo and ttwtn execute• tt
4.The 5000 mcuhod of Alr'l>y dn$5 ls u10<1 10• orrnngo the A« ay of inlege,a In
ascending order.
s. Wrapper cJass i:s used 10 pass lhe primitive data types by reference.
6.parsetnUl cakes e Strrng as parameter and returns the equivatenl Jnteger.
7.lnleger daSs is rn the lava taOQ pactcage.
8. dowhHe loop run at ust once.

true and ra1se


1. A Java compile< translates high fevel language into Java Bytecode. t
2. Byte code is set of instructions or Java class file.I
3. Dala membets and method members of an object are accessed using ;. f
4. constructor method Is used to Initialize the data
members of package.f
5. The whDe statement evaluates the test after executing the body of a loop.f
6. binary()melhod to arrange an array of integers in ascending order.f
Short answer questions

1.Predict the Output (cbse)


int x=9, k=0;
int y=10;
y=++x;
x+=y;
k=x;
What will be the value of k?
Ans20

2.Predict the output


double0Qty = {46, 42, 13, 6.5, 87.5};
System.out.println(Qty[3]);

Ariswer13

3. The following code has some error(s). Rewrite the correct code underlining all the corrections. Also
categorize the loop as Entry I Exit Control Loop. (miq)

int p
p = 14;
do;
p = p-2;
System.out.display ln(p );
}while p >= 2

Answer
int p· //error 1
p = 14;
do II error 2
{ 11 error 3
p = p-2;
System.out.println(p);
}while( p >= 2):// error 4

Exit control loop

4.Differentiate between= and== operator in JAVA

Answer
= is an assignment operator
== is a comparison operator
5,What is the purpose of using default in a switch statement? (miq)

Ans If there is no match for the expression with any case group in switch statement, the
statements in the default part are executed.

6. What is the need of NM?

ans

a Java interpreter, called the Java Virtual Machine (JVM), translates

the bytecode into machine code and then executes it. This makes Java

programs platform independent and highly portable

7.. Why is wrapper class used in Java?

Ans
These classes wrap the primitive datatype into an objeQt of that class.

8.. What is the purpose of an IDE?

ans
There are a wide variety of Java Integrated Development Environments (IDEs) available
in the market that come equipped with a text editor and a Java compiler thus simplifying
writingy compiling and executing Java programs. Most of them are freely downloadable
from the Internet. We will be using the open source and free Java Net Beans IDE for
writing Java programs.

9.ln NetBeans, by default, what is the name of a package?

ans
by default, names the package with the same name as the project, except that it is in all
lower case.

IO.Why assert statements are used in coding?

Ans
When developing your Java pro ra . .
your code g ms, it is good program ming practice to use assert stateme nts
to debug

11.Find the error and give correct code

int X = 1;

while .( x <=5 );

X = X +1;

ans

infinite loop because no increment condition so it will always be


true.

12 What are comment entries in Java? Mention two ways to give comments.
Answer
Comments are used in code by programmers to document their
programs - to provide
explanatory notes to other people who read the code.
i)Beginning a comment line with two consecutive forward slashe
s (//)
ii)Writing the comment between the symbo ls/* and*/

long answe r questions(5-10)

1.Pred ict the output of the following code; Also categorize the
loop as Entry / Exit Control
Loop. (cbse)

int j=1,s= 0;
while (j<10)
{
System .out.pr int(j+" +");
s=s+j;
j=j+j% 3;
}
System.out.println("="+s);

Answ er1+2 +4+5+ 7+8+= 27


Entry Control Loop

2.Write a method in Java to display Area of a square.


Answ er
static double square area (double side)
{ return (side* side);
}

example
3:Differentiate between return type and method arguments with a suitable
Answer
return type method name(list of parameters separated by commas)
{ statements
return (statement)
}
eg.
static double rectangle_area (double length, double breadth)
{
return (lengt h* breadth);
}

a variable. Give
4. What are variables? What are the rules to be followed while naming
example.
program
Ans A variable is a placeholder for data that can change its value during
execution. a variable is the name for a storage location in the computer's
internal memory.
1. Variable names can begin with either an alphabetic character, an underscore
with a
L), or a dollar sign($ ). However, convention is to begin a variable name
letter. They can consist of only alphabets, digits, and underscore.
le names .
2. Variable names must be one word. Spaces are not allowed in variab
Under scores are allowed.
3. Variable Name must not be a reserved word.
For examp le - int.
letters
4. Java is a case-sensitive language. Variable names written in capital
differ from variable names with the same spelling.

le example.
6.How are exceptions handled in Java? Explain with the help of a suitab
(miq)
Ans
s it to
An error situation that is unexpected in the program execution and cause
terminate unexpectedly is called an exception.
Java provides the following keywords to handle an exception:
tion(s).
try - A try block surrounds the part of the code that can generate excep
exception
catch - The catch blocks follow a try block. A catch block contains the
handl er - specific code that is executed when the exception occurs.
The optional finally block is always executed when the try block exits.
For example Division by zero exception:
try
{
int quotient= divide(10,0);
System.out. println(quotient);
}
catch (Exception e)
{
System.out. println( e .getMessage());
}

Q.7 What is the difference between a while and a


do-while loop

1. A while loop is an entry controlled loop - it tests


for a cond ition prior to runni ng a block of
code .do-w hile loop is an exit control loop it tests for
a condition after runni ng a block of
code.
2. A while loop runs zero or more times Body of loop
may neve r be exec uted

do-while loop runs once or more times but at least


once.
3. The varia bles in the test condition must be initial
ized prior to enter ing the loop struc ture.
It is not nece ssary to initialize the varia bles in the
test cond ition prior to enter ing the loop
struc ture.

Q8 Write the code to input name from standard keyboard and displa
y in java outpu t windo w
Ans

impor t java. util. Scanner;

Scann er user_input = new Scanner(System.in);

Q9 Write the statem ents to create an objec t name d bookl


of the class Book

Ans

public static void main( String [] args) {

Book bookl = new Book();}

String name = user_input.next();


System.out.println( name) ;

Q10 a.Sagar has ,declared an array whose last element is having an index
/position a~ 10. What would be the size of
this array and why ?

b. Identify the property of an array which is used to find its size.

c. What is a thread in JAVA?

Ans
a. I I

B. length
c.parts of program that can execute a different task independently at the same time.

( Q11. int□ marks= {103, 144, 256, 346};

int key= 256;

a.Write the statement to return the index of the array where the key is present.

b. wl"iat will happen If the key is not found in the array?

c. For sorting the array, which class we need to import?

Ans

a.int index= Arrays.binarySearch(marks,key);

b.lf the key is not found in the array, the binarySearch method returns -1.

c.java.util.Arrays class

q12.a. Write a user defined method that calculate simple interest. (miq)

b. Identify the valid variable names from the following

Total •narks, int , marks$, marks4

Ans

a. static double interest (double p, double r, double t )

return( p*r*t);

b. Invalid space

Invalid special character

Valid
Valid

q13. a. What is the purpose of each of the following in exception handlir,g

I.try

II.catch
r11.finally

b. Which method is used to print the error db


cause Yexception?
Ans

a. try {

II Part of the program where an exception might occur

catch (exceptiontypel argument!) {

// Handle exception of the exceptiontypel

finally {

//Code to be executed when the try block exits

b. getM essag e() method of the Exception class to print the error that
caused the exception

014. Rewrite the following code using WHILE loop:


int x=100;
for(int i=2;i<=22;i=i+4)
{
jTextArea1 .append("\n"+(i+x));
x=x-2 ;
}

Ans
int x=1 00,i=2;
while( i<=22 )
{
jTextArea1 .append("\n"+(i+x));
x=x-2 ;
i=i+4;}

Unit test
01 Write the output of following code :
class A
{ . .
public static void main(Strmg args
□)
{
int x;
X =
10;
if(x ==
10)
{
int y = 20;
System.out.print("x and y: "+ x + " " + y);
y = x*2;
}
y = 100;
System.out.print( 11x and y: 11 + x + 11 11 +
y);}
}

Q 2 What is Datatype ? Name the datatype used for storing fractional value in
any variable in JAVA ?

Q3 Is Java a case sensitive language ? Justify your answer

Q 4 Identify the property of an array which is used to find its size.

Q 5 Find the output of the following code. How many times will the loop be executed ?
for (int count = 1; count <= 1O; count = count + 2)
{
System.out.println (count);
}

Q 6 Define Variable. Write the code to declare a variable to store your age

Q7 Why is Java known as a Platform independent language ?

Q 8 Differentiate between While and Do· while loop

Q9 Consider the following code. What will be the _output of following program
and why?
public class SwitchDemo {
public static void main (String[] args)
{
int day= 6;
String dayname = "";
switch (day)
{
case 1 : dayname = "Monday"·
break; '
case 2 : dayname = "Tuesday"·
break; '
case 3 : dayname = "Wednesday"·
break; '
case 4 : dayname = "Thursday";
break;
case 5 : dayname = "Friday";
break;
case 6: dayname = "Saturday";
break;
case 7: dayname = "Sunday";
break;
default: dayname = "Invalid day";
}
System.out.println(dayname);
}
}

q10.Find the output of the following code


public class WhileDemo
{
public static void main (String [ ] args)
{
int number = 1;
while(numb er <= 5) {
System.out. print("Squar e of" + number);
System.out: println("=" + number*number);
++number;
}
}
}
What is use of ++ operator in the above code ?

Q11. Define Arrays. Sagar has declared an array whose last element is
having an index/positi on as 10. What would be the size of this array
and why?

Q12 What are User defined methods in Java? Write a program to find the area of
rectangle

013 .. What are String Class Methods in Java? Consider the statement
String name = "Welcome Akshita Singhal". 5
Write a single line Java code using String methods to perform the
following :
(a) Convert the name to Uppercase.
(b) Replace "Welcome" by "Hello" in the given string.
(c) Check whether the name contains "Sin" in it or not
(d) Add a new string "You have won the jackpot" at the end of original
string.

Q 14.Differentiate between Char and String in Java. Read the code carefully and give its output :
package javaprogarms;
public class StringDemo{
public static void main(StringOargs)
{
String myString = "Hello Everyone";
System.out.println(myString.toUpperCase());
System.out.println(myString.indexof('E'));
System.out.println(myString .replace("Hello", "Yellow"));
System.out.println(myString.contains("Hill"));
}
}

Q 15 .Write the output : 3


String strl="Hello";
String str2="Hello ";
String str3 = new String ("Hello") // Using constructor.
If(strl == str2)
System.out .println("Eq ual 1");
else
System.ou t.println("N ot Equal 1");
If(str1 == str3)
System.ou t.println("E qual 2");
else
System.ou t.println("I am constructed using constructor,
hence not interned");
lf(str1 .equals(str 3))
System.ou t.println("E qual 3");
else
System.ou t.println("N ot Equal 3"};
Java qs

1 Mr. Sahil, a programmer in a VISA processing company,


has written the following code:
int ch=lnteger.parselntUTextField1 .getText());
switch(ch)
{ case 1: jTextField2.setText("Short Term Single Entry Visa Granted");
case 2: jTextField2.setText("Short Term Multiple Entry Visa Granted");
case 3: jTextField2.setText("Long Term Single Entry Visa Granted");
case 4: jTextField2.setText("Long Term Multiple Entry Visa Granted");
default: jTextField2.setText("lnvalid Entry"); }

.No matter what value is being entered in the text field jTextF
ield1, this program always give a
message "Invalid Entry". Help Mr. Sahil in identifying the
problem and its reason. Also sugge st
him a suitable correction in the code.

2Ms. Meena is not able to understand the statement "Java


is a case sensitive language"• Help
her in understanding the above mentioned statement by
giving suitable exam ple

3Wha t will be displayed in jTextArea1 aftP-r the following


code is executed:
inti;
for(i=1 0;i<50 ;i=i+3 0)
{ i=i+15 ; jTextA rea 1.append(""+i); }
jTextA rea 1.append("\n"+i);

4 Rewr ite the follow ing code using do while loop:


int num=lnteger.parselntGTextField1 .getText());
while (num <=40 )
{ jOptio nPan e1 .show Mess ageD ialog( null,n um); num=
num* 20; }
jOptio nPan e1 .show Mess ageD ialog( null,"B ye Bye");

5The follow ing code has error(s). Rewr ite the corre ct
code under lining all the corrections made :
value 1 =1, value 2=2;
while (value 1 <valu e2)
jTextA rea 1.app end ("\n"+value1 *value 2;
value 1++ }
Ans

1.1. = = operator As = operator is assignment operator which will be used to assign the values to
any variable/constant while = = is comparison operator for equality.
(1 Mark for correct answer) (1 Mark for correct explanation)
11. int num1=5, num2=10; num1=num1+5; num2=num2-5;
(½ Mark for each correct statement)

1.ln absence of break 'fall through' condition occurs. As a result control will not be able to come
out of the switch block after first matching. So all the messages will be overwritten by the last
message i.e. "Invalid Entry" due to setText() method.
He should use break statement in each case.
(1 Mark for correct identification of the problem and reason) (1 Mark for correct correction)

2.Java is a case sensitive language as java distinguish between uppercase and lowercase very
strictly. For example:
int num1, Num1;
Although both variable have same name in the above statement but java will treat them two
different variables due to first character in different case.
(1 Mark for correct answer)

3.25
55
(½ Mark for each correct output)

411. . int num=lnteger.parselnt0TextField1 .getText()); do {


jOptionP ane1 .showMe ssageDi alog(nul l,num); num=num *20; } while(nu m<=40);
jOptionP ane1 .showMe ssageDi alog(nul l, "Bye Bye");
(2 Mark for correct code in do while)

Sint value1 =1, value2=2 ; //Correc tion 1 while(value1 <value2)


{iTextAre a1 .append ("\n"+value1 *value2) ; //Correc tion 2 & 3 value1++;
//Correc tion 4 }
(½ Mark for each correct correctio n)
Write the value that Will b
e assig
1 x = 20 - 5 + 3 * 20/S· ned to variabl 8 .
(b) Consider the state ' x after executing the following statement : t
ment • ch .
What is the datatype of v : orce = 'Y';
'choice'. 1 anabte choice? Wr" l
.le k" .
(C) Whl wor rng in Netb rte a Java statement to declare the variable
next line without b eans IDE, Amit wa t th
. reaking the word . n s at the text in a Text area should move to the
(d) Wnte a Java statement t . · Which properties would help him to do that? 1
1
area named jTextArea1 °· Append a string "ABC" to the text that is already in the text

Ans (a) Value of x will be


27
the variable 'choice'· ch h · ~b) Datatype of variable choice is char. Java statement to declare
true (d) Java statem~nt ~r-~ orce; choice= 'Y'; (c) Set LineWrap and WordWrap properties to
rs. JTextArea1 .append("ABC");

(a) Write the values of


=
int p 11; int = .
_r a~~ s after the execution of the following code:
q 21, rnt r, rnt s; r = ++q; s = p++; r+ +;

(_b) W~a~ will b~ displayed in jTextField1 and jTextField2 after the following code is executed:
nd1
~n"t ~,t~ =~; =
rnt N 35; while (N > 12) { ndigits = ndigits + 1; N = N - 10; } jTextField1 .setText
( +nd1g1ts); JTextField2.setText (" "+N);

(c) Write the value of C after executing the following code:


int P; int R = 8; int oddNum; int C = 0; for (P = 1; p < R; p = P+3) { oddNum = P%2; if (oddNum
== 1) { C =C + 1; } }

(d) Write the value that will be stored in the variable t after the execution of the following code.
How many times will the loop execute?
int sum = O; int score = O; double t; do { score = score + 1; sum = sum + score; } while(score <
=3); t =sum/3;
(e )The following code has error( s ). Rewrite the correct code underlining all the corrections
made:

int j; int i = 15; int flag = 1; while 0=2 j<i; j++) { if(i % j = 0) { flag == O; break; } }

Ans
(a) Value of r = 23 ands= 11
(b)3 will be displayed in jTextField1, 5 will be displayed in jTextField2.
(c) Value of C = 2
(d) Value oft= 3.0, 4 times will the loop execute. .
(e) The correct code is: int j; inti = 15; int flag = 1; for (j=2; j<i; j++) { if (i%j==0) { flag = O; break,
}}

us1.·ng IF ELSE statement instead of


.
Rewrite t h e f allowing program code
SWITCH construct.
String direction;
char command=jTex tFieldl.getrext( ) .trim();
switch (command)

case ',.' . direction "top";


break;
case '<' : direction "left";
break;
case '>' : direction "right";
break;
default: direction "Unknown";
}

1.What value is assigned to num in the following code fragment, when choice is 2?
switch (choice)
{
case 1: num=10; break;
case 2: num=20;
case 3: num=30; break;
default: num=0;
}
In the above code, what is the significance of break statement?

2.The following code has some error(s). Rewrite the correct code underlining all the corrections
made.
int marks=
Int.parseInt(jTextFieldl.getText());
if (marks >= 60 and marks <= 100)
{
jTextField2.setText('First Division');
else (marks >=50 and marks <=59)
{
jTextField2.setText('Second Division'); '
}
·
stat .
m co d e using IF ELSE ent ' 0stead o f SWITCH
llow ing prog ra em construct.
rite the fo
3. Rew
; ·
String direction iefd1 .getText().trim();
nd=jTex tF
. char comma
and)
switch (comm
{
on = "top";
case w: directi
break;
tion= "left";
case'<': direc
break;
on = "righr;
case '>': directi
break;
: directi on = "Unknown"·I
default
}

• • I

J •

4
. :

:f'.>
i
--c-7

~ Yl
v
®
~

~
. I
~ ~c

t ·f

,_ ,_ f_ /L_ /_ /_ / I I I I
,.---4
~
?----
~

,:- \
~
(

~
'

You might also like