SlideShare une entreprise Scribd logo
1  sur  11
Télécharger pour lire hors ligne
https://www.facebook. com/Oxus20
PART I – Single and Multiple choices, True/False and Blanks:
1) ............. If I have a variable that is a constant, then I must define the
variable name with capital letters.

 True

 False

 False -

Because you don't have to define

the constant variable name with CAPITAL;
but it is recommended.

2) If you forget to put a closing quotation mark on a string, what kind error will be
raised?

 A compilation error

 A runtime error

 A logic error

3) ............. What is the size of a char?

 4 bits
 8 bits

 7 bits
 16 bits

 16 bits

- Because the char data type is a single

16-bit Unicode character. It has a minimum value
of 'u0000' (or 0) and a maximum value
of 'uFFFF' (or 65,535 inclusive).

4) If a program compiles fine, but it produces incorrect result, then the program
suffers __________.

 A compilation error

A logic error -

 A runtime error

Because the program compiles fine,

also there is no Runtime Error because the program
does not crush.

 A logic error

5) Which of the following are the reserved words?

 public

 static

 void

 class

Abdul Rahman Sherzad

All of them are Reserved Words (Key
Words) in JAVA.

Page 1 of 11
https://www.facebook. com/Oxus20
6) ............. The operator, +, may be used to concatenate strings together as well
as add two numeric quantities together.

 True

 False

 True - Because:
String full_name = "Abdul Rahman " + "Sherzad";
int sum = 2 + 3;

7) Analyze the following code.
public class Test {
public static void main(String[] args) {
System.out.println(myMethod(2));
}
public static int myMethod(int num) {
return num;
}
public static void myMethod(int num) {
System.out.println(num);
}
}

 The program has a compile error because the two methods myMethod have the same signature.
 The program has a compile error because the second myMethod method is defined, but not invoked in the main method.
 The program runs and prints 2 once.
 The program runs and prints 2 twice.

The method name and parameter list are part of method
signature. Declaration of two methods with same
signature is not possible because The Java compiler
is able to distinguish the difference between the
methods through their method signatures.

8) Math.pow(4, 1 / 2) returns __________.

2

 2.0

0

 0.0

1

 1.0

 1.O – Because:


1 / 2 = 0 due to the INTEGER Division



Math.pow(4, 0) = 1.0 since every number to the
power is 1; on the other hand the pow() method
returns double thus 1 becomes 1.0

Abdul Rahman Sherzad

Page 2 of 11
https://www.facebook. com/Oxus20
9) Which of the following is a valid identifier?

 $343

 class

 9X

 8+9

 radius

 _999



All variable names must begin with a letter
of the alphabet, an underscore ( _ ), or a
dollar sign ($).



You cannot use a java keyword (reserved
word) for a variable name.

10) Which of the following is a constant, according to Java naming conventions?

 MAX_VALUE

 Test

 read

 ReadInt

Use ALL_UPPER_CASE for your named constants,

 COUNT

 Variable_Name

separating words with the underscore character.
For example, use TAX_RATE rather
than taxRate or TAXRATE.

11) Analyze the following code:

Code 1:
int number = 45;
boolean even;
if (number % 2 == 0)
even = true;
else
even = false;

Code 2:
boolean even = (number % 2 == 0);

 Code 1 has compile errors.
 Code 2 has compile errors.
 Both Code 1 and Code 2 have compile errors.
 Both Code 1 and Code 2 are correct, but Code 2 is better.

boolean even = (number % 2 == 0);


The above expression interprets as if the
number is completely divisible by 2 even will
be set to true else even will be set to false.

Abdul Rahman Sherzad

Page 3 of 11
https://www.facebook. com/Oxus20
12) What is the exact output of the following code?

double area = 3.5;
System.out.print("area");
System.out.print(area);

 3.53.5

 3.5 3.5

 area3.5

 area 3.5

System.out.print("area"); // the word area will be printed
as it appears between "" with cursor on same line.
System.out.println(area); // the word area will be
interpreted as 3.5 this time because it does not appear
between "".

13) How many times will the following code print "Welcome to OXUS 20"?
int count = 0;
while (count++ < 10) {
System.out.println("Welcome to OXUS 20");
}

8

9

 10

 11

The above code can be written as follow:
int count = 0;
while (count < 10) {
System.out.println("Welcome to OXUS 20");
count++;
}


The loop start from 0 (0 is inclusive) and continues
until 10 (10 is not included)



Interval demonstration [0, 10)

14) What is the result of -7 % 5 is _____?

2
0

 -2
 -7

Abdul Rahman Sherzad

JAVA language developers decided to choose the sign of the
result equals the sign of the dividend in modulus
expression. Thus, in expression -7 % 5 the dividend is -7,
so result of modulus will be evaluated to -2.

Page 4 of 11
https://www.facebook. com/Oxus20
15) You should fill in the blank in the following code with ______________.
public class Test {
public static void main(String[] args) {
System.out.print("The grade is ");
printGrade(78.5);
System.out.print("The grade is ");
printGrade(59.5);
}
public static __________ printGrade(double score) {
if (score >= 90.0) {
System.out.println('A');
} else if (score >= 80.0) {
System.out.println('B');
} else if (score >= 70.0) {
System.out.println('C');
} else if (score >= 60.0) {
System.out.println('D');
} else {
System.out.println('F');
}
}
}

 int

 double

 boolean

 char

 void

 String

 void

is the correct answer because the

printGrade() method does not return anything; it
simply prints the result.

16) The following code fragment reads in two numbers:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int i = input.nextInt();
double d = input.nextDouble();
}
What are the correct ways to enter these two numbers?

 Enter an integer, a space, a double value, and then the Enter key.
 Enter an integer, two spaces, a double value, and then the Enter key.
 Enter an integer, an Enter key, a double value, and then the Enter key.
 Enter a numeric value with a decimal point, a space, an integer, and then the Enter key.
Abdul Rahman Sherzad

Page 5 of 11
https://www.facebook. com/Oxus20
PART II – Write output of the followings programs:
1. What output is produced by the following program?
public class Test {
public static void main(String[] args) {
int limit = 100, num1 = 10, num2 = 20;
if (limit <= limit) {
if (num1 == num2)
System.out.println("Tricky Question");
System.out.println("OXUS 20");
}
System.out.println("OXUS means (Amu Darya)");
}
}

OXUS 20
OXUS means (Amu Darya)

Following is the correct indentation and syntax of above program:
public class Test {
public static void main(String[] args) {
int limit = 100, num1 = 10, num2 = 20;
if (limit <= limit) {
if (num1 == num2) {
System.out.println("Tricky Question");
}
System.out.println("OXUS 20");
}
System.out.println("OXUS means (Amu Darya)");
}
}

2. What output is produced by the following program?
public class Test {
public static void main(String[] args) {
char c1 = 'A';
char c2 = 'B';
System.out.println(c1 + c2);
}
}

131

Why the output is 131? Because:



'B' = 66



Abdul Rahman Sherzad

'A' = 65

'A' + 'B' => 65 + 66 = 131

Page 6 of 11
https://www.facebook. com/Oxus20
1. What output is produced by the following program?
public class Test {
public static void main(String[] args) {
char c1 = 'A';
char c2 = 'B';
System.out.println("" + c1 + c2);
}
}

Why the output is AB? Because java calculates the expression from

AB

left to right as follow:


"" + c1 = "A"



"A" + c2 = "AB" // String plus char will be converted to String



Thus output will be AB

// String plus char will be converted to String

1. What output is produced by the following program?
public class Test {
public static void main(String[] args) {
char c1 = 'A';
char c2 = 'B';
System.out.println(c1 + c2 + "");
}
}
Why the output is 131? Because java calculates the expression from

131

left to right as follow:


c1 + c2 => 'A' + 'B' => 65 + 66 = 131

// Both will be

considered as interger


Now 131 + "" = "131" // integer plus String will be evaluated to
String



Abdul Rahman Sherzad

Thus output will be 131

Page 7 of 11
https://www.facebook. com/Oxus20
PART III – Write the program for the following s:
1. Write a method called isAlphaNumeric that accepts a character parameter and returns
true if that character is either an uppercase, lowercase or numeric letter.

Method1: Using Regular Expression
public static boolean isAlphanumeric(String input) {
if (input == null || input.length() == 0)
return false;
if (input.matches("[a-zA-Z0-9]+")) {
return true;
} else {
return false;
}
}

Method2: Using for loop
public static boolean isAlphanumeric(String input) {
if (input == null || input.length() == 0)
return false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) {

return false;
}
}
return true;
}

Method3: Using for loop with Character Wrapper Class
public static boolean isAlphanumeric(String input) {
if (input == null || input.length() == 0)
return false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (!Character.isLetterOrDigit(c)) {
return false;
}
}
return true;
}

Abdul Rahman Sherzad

Page 8 of 11
https://www.facebook. com/Oxus20
2. Write a method to count the number of occurrences of a char in a String?

Method1: Using loop with support of String methods
public static int countOccurrences(String strInput, char needle) {
int count = 0;
for (int i = 0; i < strInput.length(); i++) {
if (strInput.charAt(i) == needle) {
count++;
}
}
return count;
}

Method1: Using Advanced for loop
public static int countOccurrences(String strInput, char needle) {
int count = 0;
for (char c : strInput.toCharArray()) {
if (c == needle) {
count++;
}
}
return count;
}

Method1: Using String replaceAll() method
public static int countOccurrences(String strInput, char needle) {
return strInput.length() - strInput.replaceAll(String.valueOf(needle), "").length();
}
return strInput.length() - strInput.replaceAll(String.valueOf(needle), "").length();
Consider strInput = "Abdul Rahman Sherzad" and needle = 'a'
strInput.length() // 20
strInput.replaceAll(String.valueOf(needle), ""); // Abdul Rhmn Sherzd
"Abdul Rhmn Sherzd".length() // 17
Return 20 – 17 = 3 // Thus, letter 'a' appears 3 times in "Abdul Rahman Sherzad".

Abdul Rahman Sherzad

Page 9 of 11
https://www.facebook. com/Oxus20

3. Write a method called sumRange that accepts two integers as parameters that
represent a range. Print an error message and return zero if the second parameter
is less than the first. Otherwise, the method should return the sum of the integers
in that range (both first and second parameters are inclusive).
public static int sumRange(int start, int end) {
int sum = 0;
if (end < start) {
System.err.println("ERROR: Invalid Rangen");
} else {
for (int num = start; num <= end; num++) {
sum = sum + num;
}
}
return sum;
}

4. Write a method called isAlpha that accepts a String as parameter and returns true
if the given String contains only either uppercase or lowercase alphabetic letters.

Method1: Using Regular Expression
public static boolean isAlpha(String input) {
if (input == null || input.length() == 0)
return false;
if (input.matches("[a-zA-Z]+"))
return true;
return false;
}

Method2: Using for loop
public static boolean isAlpha(String input) {
if (input == null || input.length() == 0)
return false;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) {
return false;
}
}
return true;
}
Note: similar functionality is provided by the Character.isLetter(c) method as follow:

if (!Character.isLetter(c)) { return false; }

Abdul Rahman Sherzad

OX
US20

Page 10 of 11
https://www.facebook. com/Oxus20

Society
is

the

premier

Computer

society

Science

professionals

and

founded

of
IT
in

March 2013.
The

society's

goal

is

to

provide

information

and

assistance

to

Computer

Science

professionals, increase their job performance and overall agency function by providing
cost effective products, services and educational opportunities. So the society believes
with the education of Computer Science and IT they can help their nation to higher
standards of living.

Follow us on Facebook,

https://www.facebook.com/Oxus20

Abdul Rahman Sherzad

Page 11 of 11

Contenu connexe

En vedette

De vry math 221 all ilabs latest 2016 november
De vry math 221 all ilabs latest 2016 novemberDe vry math 221 all ilabs latest 2016 november
De vry math 221 all ilabs latest 2016 novemberlenasour
 
Cs2 ah0405 softwarerequirements
Cs2 ah0405 softwarerequirementsCs2 ah0405 softwarerequirements
Cs2 ah0405 softwarerequirementsjayyu123
 
Math solvers week 1
Math solvers week 1Math solvers week 1
Math solvers week 1sinclair4
 
Logic Model and Education
Logic Model and EducationLogic Model and Education
Logic Model and Educationdledingham
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 
Hsv 405 midterm exam answers
Hsv 405 midterm exam answersHsv 405 midterm exam answers
Hsv 405 midterm exam answersDennisHine
 
Software Engineering Fundamentals - Svetlin Nakov
Software Engineering Fundamentals - Svetlin NakovSoftware Engineering Fundamentals - Svetlin Nakov
Software Engineering Fundamentals - Svetlin NakovSvetlin Nakov
 
Requirement Engineering Lec.1 & 2 & 3
Requirement Engineering Lec.1 & 2 & 3Requirement Engineering Lec.1 & 2 & 3
Requirement Engineering Lec.1 & 2 & 3Ahmed Alageed
 
S S Structured Essay Booklet
S S  Structured  Essay BookletS S  Structured  Essay Booklet
S S Structured Essay Bookletvikhist
 
Introduction to computer hardware
Introduction to computer hardwareIntroduction to computer hardware
Introduction to computer hardwareMirea Mizushima
 
Software Engineering Sample Question paper for 2012
Software Engineering Sample Question paper for 2012Software Engineering Sample Question paper for 2012
Software Engineering Sample Question paper for 2012Neelamani Samal
 
Logical reasoning questions and answers
Logical reasoning questions and answersLogical reasoning questions and answers
Logical reasoning questions and answersMydear student
 
Software engineering Questions and Answers
Software engineering Questions and AnswersSoftware engineering Questions and Answers
Software engineering Questions and AnswersBala Ganesh
 
Lecture 2 Software Engineering and Design Object Oriented Programming, Design...
Lecture 2 Software Engineering and Design Object Oriented Programming, Design...Lecture 2 Software Engineering and Design Object Oriented Programming, Design...
Lecture 2 Software Engineering and Design Object Oriented Programming, Design...op205
 
software engineering notes for cse/it fifth semester
software engineering notes for cse/it fifth semestersoftware engineering notes for cse/it fifth semester
software engineering notes for cse/it fifth semesterrajesh199155
 

En vedette (15)

De vry math 221 all ilabs latest 2016 november
De vry math 221 all ilabs latest 2016 novemberDe vry math 221 all ilabs latest 2016 november
De vry math 221 all ilabs latest 2016 november
 
Cs2 ah0405 softwarerequirements
Cs2 ah0405 softwarerequirementsCs2 ah0405 softwarerequirements
Cs2 ah0405 softwarerequirements
 
Math solvers week 1
Math solvers week 1Math solvers week 1
Math solvers week 1
 
Logic Model and Education
Logic Model and EducationLogic Model and Education
Logic Model and Education
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 
Hsv 405 midterm exam answers
Hsv 405 midterm exam answersHsv 405 midterm exam answers
Hsv 405 midterm exam answers
 
Software Engineering Fundamentals - Svetlin Nakov
Software Engineering Fundamentals - Svetlin NakovSoftware Engineering Fundamentals - Svetlin Nakov
Software Engineering Fundamentals - Svetlin Nakov
 
Requirement Engineering Lec.1 & 2 & 3
Requirement Engineering Lec.1 & 2 & 3Requirement Engineering Lec.1 & 2 & 3
Requirement Engineering Lec.1 & 2 & 3
 
S S Structured Essay Booklet
S S  Structured  Essay BookletS S  Structured  Essay Booklet
S S Structured Essay Booklet
 
Introduction to computer hardware
Introduction to computer hardwareIntroduction to computer hardware
Introduction to computer hardware
 
Software Engineering Sample Question paper for 2012
Software Engineering Sample Question paper for 2012Software Engineering Sample Question paper for 2012
Software Engineering Sample Question paper for 2012
 
Logical reasoning questions and answers
Logical reasoning questions and answersLogical reasoning questions and answers
Logical reasoning questions and answers
 
Software engineering Questions and Answers
Software engineering Questions and AnswersSoftware engineering Questions and Answers
Software engineering Questions and Answers
 
Lecture 2 Software Engineering and Design Object Oriented Programming, Design...
Lecture 2 Software Engineering and Design Object Oriented Programming, Design...Lecture 2 Software Engineering and Design Object Oriented Programming, Design...
Lecture 2 Software Engineering and Design Object Oriented Programming, Design...
 
software engineering notes for cse/it fifth semester
software engineering notes for cse/it fifth semestersoftware engineering notes for cse/it fifth semester
software engineering notes for cse/it fifth semester
 

Similaire à OXUS20 JAVA Programming Questions and Answers PART I

Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfmayorothenguyenhob69
 
1 Midterm Preview Time allotted 50 minutes CS 11.docx
1  Midterm Preview Time allotted 50 minutes CS 11.docx1  Midterm Preview Time allotted 50 minutes CS 11.docx
1 Midterm Preview Time allotted 50 minutes CS 11.docxhoney725342
 
ExamName___________________________________MULTIPLE CH.docx
ExamName___________________________________MULTIPLE CH.docxExamName___________________________________MULTIPLE CH.docx
ExamName___________________________________MULTIPLE CH.docxgitagrimston
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
21: Which method determines if a JRadioButton is selected?
21: Which method determines if a JRadioButton is selected?21: Which method determines if a JRadioButton is selected?
21: Which method determines if a JRadioButton is selected?sukeshsuresh189
 
6: Which of the following statements about creating arrays and initializing t...
6: Which of the following statements about creating arrays and initializing t...6: Which of the following statements about creating arrays and initializing t...
6: Which of the following statements about creating arrays and initializing t...sukeshsuresh189
 
202: When the user clicks a JCheckBox, a(n) occurs.
202: When the user clicks a JCheckBox, a(n) occurs.202: When the user clicks a JCheckBox, a(n) occurs.
202: When the user clicks a JCheckBox, a(n) occurs.sukeshsuresh189
 
3: A(n) ________ enables a program to read data from the user.
3: A(n) ________ enables a program to read data from the user.3: A(n) ________ enables a program to read data from the user.
3: A(n) ________ enables a program to read data from the user.sukeshsuresh189
 
22: The logical relationship between radio buttons is maintained by objects o...
22: The logical relationship between radio buttons is maintained by objects o...22: The logical relationship between radio buttons is maintained by objects o...
22: The logical relationship between radio buttons is maintained by objects o...sukeshsuresh189
 
19: When the user presses Enter in a JTextField, the GUI component generates ...
19: When the user presses Enter in a JTextField, the GUI component generates ...19: When the user presses Enter in a JTextField, the GUI component generates ...
19: When the user presses Enter in a JTextField, the GUI component generates ...sukeshsuresh189
 
12: When an object is concatenated with a String
12: When an object is concatenated with a String12: When an object is concatenated with a String
12: When an object is concatenated with a Stringsukeshsuresh189
 
5: Every Java application is required to have
5: Every Java application is required to have5: Every Java application is required to have
5: Every Java application is required to havesukeshsuresh189
 
15: Which method call converts the value in variable stringVariable to an int...
15: Which method call converts the value in variable stringVariable to an int...15: Which method call converts the value in variable stringVariable to an int...
15: Which method call converts the value in variable stringVariable to an int...sukeshsuresh189
 
16: Which of the following is the method used to display a dialog box to gath...
16: Which of the following is the method used to display a dialog box to gath...16: Which of the following is the method used to display a dialog box to gath...
16: Which of the following is the method used to display a dialog box to gath...sukeshsuresh189
 

Similaire à OXUS20 JAVA Programming Questions and Answers PART I (20)

Review Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdfReview Questions for Exam 10182016 1. public class .pdf
Review Questions for Exam 10182016 1. public class .pdf
 
1 Midterm Preview Time allotted 50 minutes CS 11.docx
1  Midterm Preview Time allotted 50 minutes CS 11.docx1  Midterm Preview Time allotted 50 minutes CS 11.docx
1 Midterm Preview Time allotted 50 minutes CS 11.docx
 
ExamName___________________________________MULTIPLE CH.docx
ExamName___________________________________MULTIPLE CH.docxExamName___________________________________MULTIPLE CH.docx
ExamName___________________________________MULTIPLE CH.docx
 
Ch4
Ch4Ch4
Ch4
 
Session 5-exersice
Session 5-exersiceSession 5-exersice
Session 5-exersice
 
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
Testing techniques
Testing techniquesTesting techniques
Testing techniques
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt07-Basic-Input-Output.ppt
07-Basic-Input-Output.ppt
 
21: Which method determines if a JRadioButton is selected?
21: Which method determines if a JRadioButton is selected?21: Which method determines if a JRadioButton is selected?
21: Which method determines if a JRadioButton is selected?
 
6: Which of the following statements about creating arrays and initializing t...
6: Which of the following statements about creating arrays and initializing t...6: Which of the following statements about creating arrays and initializing t...
6: Which of the following statements about creating arrays and initializing t...
 
202: When the user clicks a JCheckBox, a(n) occurs.
202: When the user clicks a JCheckBox, a(n) occurs.202: When the user clicks a JCheckBox, a(n) occurs.
202: When the user clicks a JCheckBox, a(n) occurs.
 
3: A(n) ________ enables a program to read data from the user.
3: A(n) ________ enables a program to read data from the user.3: A(n) ________ enables a program to read data from the user.
3: A(n) ________ enables a program to read data from the user.
 
22: The logical relationship between radio buttons is maintained by objects o...
22: The logical relationship between radio buttons is maintained by objects o...22: The logical relationship between radio buttons is maintained by objects o...
22: The logical relationship between radio buttons is maintained by objects o...
 
19: When the user presses Enter in a JTextField, the GUI component generates ...
19: When the user presses Enter in a JTextField, the GUI component generates ...19: When the user presses Enter in a JTextField, the GUI component generates ...
19: When the user presses Enter in a JTextField, the GUI component generates ...
 
12: When an object is concatenated with a String
12: When an object is concatenated with a String12: When an object is concatenated with a String
12: When an object is concatenated with a String
 
5: Every Java application is required to have
5: Every Java application is required to have5: Every Java application is required to have
5: Every Java application is required to have
 
15: Which method call converts the value in variable stringVariable to an int...
15: Which method call converts the value in variable stringVariable to an int...15: Which method call converts the value in variable stringVariable to an int...
15: Which method call converts the value in variable stringVariable to an int...
 
16: Which of the following is the method used to display a dialog box to gath...
16: Which of the following is the method used to display a dialog box to gath...16: Which of the following is the method used to display a dialog box to gath...
16: Which of the following is the method used to display a dialog box to gath...
 

Plus de Abdul Rahman Sherzad

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanAbdul Rahman Sherzad
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsAbdul Rahman Sherzad
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLAbdul Rahman Sherzad
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and ApplicationsAbdul Rahman Sherzad
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Abdul Rahman Sherzad
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and AwarenessAbdul Rahman Sherzad
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesAbdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationAbdul Rahman Sherzad
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersAbdul Rahman Sherzad
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsAbdul Rahman Sherzad
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepAbdul Rahman Sherzad
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaAbdul Rahman Sherzad
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesAbdul Rahman Sherzad
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesAbdul Rahman Sherzad
 

Plus de Abdul Rahman Sherzad (20)

Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in AfghanistanData is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
Data is the Fuel of Organizations: Opportunities and Challenges in Afghanistan
 
PHP Unicode Input Validation Snippets
PHP Unicode Input Validation SnippetsPHP Unicode Input Validation Snippets
PHP Unicode Input Validation Snippets
 
Iterations and Recursions
Iterations and RecursionsIterations and Recursions
Iterations and Recursions
 
Sorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQLSorting Alpha Numeric Data in MySQL
Sorting Alpha Numeric Data in MySQL
 
PHP Variable variables Examples
PHP Variable variables ExamplesPHP Variable variables Examples
PHP Variable variables Examples
 
Cross Join Example and Applications
Cross Join Example and ApplicationsCross Join Example and Applications
Cross Join Example and Applications
 
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
Applicability of Educational Data Mining in Afghanistan: Opportunities and Ch...
 
Web Application Security and Awareness
Web Application Security and AwarenessWeb Application Security and Awareness
Web Application Security and Awareness
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Mobile Score Notification System
Mobile Score Notification SystemMobile Score Notification System
Mobile Score Notification System
 
Herat Innovation Lab 2015
Herat Innovation Lab 2015Herat Innovation Lab 2015
Herat Innovation Lab 2015
 
Evaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan UniversitiesEvaluation of Existing Web Structure of Afghan Universities
Evaluation of Existing Web Structure of Afghan Universities
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
 
Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and Relationships
 
Create Splash Screen with Java Step by Step
Create Splash Screen with Java Step by StepCreate Splash Screen with Java Step by Step
Create Splash Screen with Java Step by Step
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Web Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and TechnologiesWeb Design and Development Life Cycle and Technologies
Web Design and Development Life Cycle and Technologies
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 

Dernier

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 

Dernier (20)

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 

OXUS20 JAVA Programming Questions and Answers PART I

  • 1. https://www.facebook. com/Oxus20 PART I – Single and Multiple choices, True/False and Blanks: 1) ............. If I have a variable that is a constant, then I must define the variable name with capital letters.  True  False  False - Because you don't have to define the constant variable name with CAPITAL; but it is recommended. 2) If you forget to put a closing quotation mark on a string, what kind error will be raised?  A compilation error  A runtime error  A logic error 3) ............. What is the size of a char?  4 bits  8 bits  7 bits  16 bits  16 bits - Because the char data type is a single 16-bit Unicode character. It has a minimum value of 'u0000' (or 0) and a maximum value of 'uFFFF' (or 65,535 inclusive). 4) If a program compiles fine, but it produces incorrect result, then the program suffers __________.  A compilation error A logic error -  A runtime error Because the program compiles fine, also there is no Runtime Error because the program does not crush.  A logic error 5) Which of the following are the reserved words?  public  static  void  class Abdul Rahman Sherzad All of them are Reserved Words (Key Words) in JAVA. Page 1 of 11
  • 2. https://www.facebook. com/Oxus20 6) ............. The operator, +, may be used to concatenate strings together as well as add two numeric quantities together.  True  False  True - Because: String full_name = "Abdul Rahman " + "Sherzad"; int sum = 2 + 3; 7) Analyze the following code. public class Test { public static void main(String[] args) { System.out.println(myMethod(2)); } public static int myMethod(int num) { return num; } public static void myMethod(int num) { System.out.println(num); } }  The program has a compile error because the two methods myMethod have the same signature.  The program has a compile error because the second myMethod method is defined, but not invoked in the main method.  The program runs and prints 2 once.  The program runs and prints 2 twice. The method name and parameter list are part of method signature. Declaration of two methods with same signature is not possible because The Java compiler is able to distinguish the difference between the methods through their method signatures. 8) Math.pow(4, 1 / 2) returns __________. 2  2.0 0  0.0 1  1.0  1.O – Because:  1 / 2 = 0 due to the INTEGER Division  Math.pow(4, 0) = 1.0 since every number to the power is 1; on the other hand the pow() method returns double thus 1 becomes 1.0 Abdul Rahman Sherzad Page 2 of 11
  • 3. https://www.facebook. com/Oxus20 9) Which of the following is a valid identifier?  $343  class  9X  8+9  radius  _999  All variable names must begin with a letter of the alphabet, an underscore ( _ ), or a dollar sign ($).  You cannot use a java keyword (reserved word) for a variable name. 10) Which of the following is a constant, according to Java naming conventions?  MAX_VALUE  Test  read  ReadInt Use ALL_UPPER_CASE for your named constants,  COUNT  Variable_Name separating words with the underscore character. For example, use TAX_RATE rather than taxRate or TAXRATE. 11) Analyze the following code: Code 1: int number = 45; boolean even; if (number % 2 == 0) even = true; else even = false; Code 2: boolean even = (number % 2 == 0);  Code 1 has compile errors.  Code 2 has compile errors.  Both Code 1 and Code 2 have compile errors.  Both Code 1 and Code 2 are correct, but Code 2 is better. boolean even = (number % 2 == 0);  The above expression interprets as if the number is completely divisible by 2 even will be set to true else even will be set to false. Abdul Rahman Sherzad Page 3 of 11
  • 4. https://www.facebook. com/Oxus20 12) What is the exact output of the following code? double area = 3.5; System.out.print("area"); System.out.print(area);  3.53.5  3.5 3.5  area3.5  area 3.5 System.out.print("area"); // the word area will be printed as it appears between "" with cursor on same line. System.out.println(area); // the word area will be interpreted as 3.5 this time because it does not appear between "". 13) How many times will the following code print "Welcome to OXUS 20"? int count = 0; while (count++ < 10) { System.out.println("Welcome to OXUS 20"); } 8 9  10  11 The above code can be written as follow: int count = 0; while (count < 10) { System.out.println("Welcome to OXUS 20"); count++; }  The loop start from 0 (0 is inclusive) and continues until 10 (10 is not included)  Interval demonstration [0, 10) 14) What is the result of -7 % 5 is _____? 2 0  -2  -7 Abdul Rahman Sherzad JAVA language developers decided to choose the sign of the result equals the sign of the dividend in modulus expression. Thus, in expression -7 % 5 the dividend is -7, so result of modulus will be evaluated to -2. Page 4 of 11
  • 5. https://www.facebook. com/Oxus20 15) You should fill in the blank in the following code with ______________. public class Test { public static void main(String[] args) { System.out.print("The grade is "); printGrade(78.5); System.out.print("The grade is "); printGrade(59.5); } public static __________ printGrade(double score) { if (score >= 90.0) { System.out.println('A'); } else if (score >= 80.0) { System.out.println('B'); } else if (score >= 70.0) { System.out.println('C'); } else if (score >= 60.0) { System.out.println('D'); } else { System.out.println('F'); } } }  int  double  boolean  char  void  String  void is the correct answer because the printGrade() method does not return anything; it simply prints the result. 16) The following code fragment reads in two numbers: public static void main(String[] args) { Scanner input = new Scanner(System.in); int i = input.nextInt(); double d = input.nextDouble(); } What are the correct ways to enter these two numbers?  Enter an integer, a space, a double value, and then the Enter key.  Enter an integer, two spaces, a double value, and then the Enter key.  Enter an integer, an Enter key, a double value, and then the Enter key.  Enter a numeric value with a decimal point, a space, an integer, and then the Enter key. Abdul Rahman Sherzad Page 5 of 11
  • 6. https://www.facebook. com/Oxus20 PART II – Write output of the followings programs: 1. What output is produced by the following program? public class Test { public static void main(String[] args) { int limit = 100, num1 = 10, num2 = 20; if (limit <= limit) { if (num1 == num2) System.out.println("Tricky Question"); System.out.println("OXUS 20"); } System.out.println("OXUS means (Amu Darya)"); } } OXUS 20 OXUS means (Amu Darya) Following is the correct indentation and syntax of above program: public class Test { public static void main(String[] args) { int limit = 100, num1 = 10, num2 = 20; if (limit <= limit) { if (num1 == num2) { System.out.println("Tricky Question"); } System.out.println("OXUS 20"); } System.out.println("OXUS means (Amu Darya)"); } } 2. What output is produced by the following program? public class Test { public static void main(String[] args) { char c1 = 'A'; char c2 = 'B'; System.out.println(c1 + c2); } } 131 Why the output is 131? Because:   'B' = 66  Abdul Rahman Sherzad 'A' = 65 'A' + 'B' => 65 + 66 = 131 Page 6 of 11
  • 7. https://www.facebook. com/Oxus20 1. What output is produced by the following program? public class Test { public static void main(String[] args) { char c1 = 'A'; char c2 = 'B'; System.out.println("" + c1 + c2); } } Why the output is AB? Because java calculates the expression from AB left to right as follow:  "" + c1 = "A"  "A" + c2 = "AB" // String plus char will be converted to String  Thus output will be AB // String plus char will be converted to String 1. What output is produced by the following program? public class Test { public static void main(String[] args) { char c1 = 'A'; char c2 = 'B'; System.out.println(c1 + c2 + ""); } } Why the output is 131? Because java calculates the expression from 131 left to right as follow:  c1 + c2 => 'A' + 'B' => 65 + 66 = 131 // Both will be considered as interger  Now 131 + "" = "131" // integer plus String will be evaluated to String  Abdul Rahman Sherzad Thus output will be 131 Page 7 of 11
  • 8. https://www.facebook. com/Oxus20 PART III – Write the program for the following s: 1. Write a method called isAlphaNumeric that accepts a character parameter and returns true if that character is either an uppercase, lowercase or numeric letter. Method1: Using Regular Expression public static boolean isAlphanumeric(String input) { if (input == null || input.length() == 0) return false; if (input.matches("[a-zA-Z0-9]+")) { return true; } else { return false; } } Method2: Using for loop public static boolean isAlphanumeric(String input) { if (input == null || input.length() == 0) return false; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) { return false; } } return true; } Method3: Using for loop with Character Wrapper Class public static boolean isAlphanumeric(String input) { if (input == null || input.length() == 0) return false; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (!Character.isLetterOrDigit(c)) { return false; } } return true; } Abdul Rahman Sherzad Page 8 of 11
  • 9. https://www.facebook. com/Oxus20 2. Write a method to count the number of occurrences of a char in a String? Method1: Using loop with support of String methods public static int countOccurrences(String strInput, char needle) { int count = 0; for (int i = 0; i < strInput.length(); i++) { if (strInput.charAt(i) == needle) { count++; } } return count; } Method1: Using Advanced for loop public static int countOccurrences(String strInput, char needle) { int count = 0; for (char c : strInput.toCharArray()) { if (c == needle) { count++; } } return count; } Method1: Using String replaceAll() method public static int countOccurrences(String strInput, char needle) { return strInput.length() - strInput.replaceAll(String.valueOf(needle), "").length(); } return strInput.length() - strInput.replaceAll(String.valueOf(needle), "").length(); Consider strInput = "Abdul Rahman Sherzad" and needle = 'a' strInput.length() // 20 strInput.replaceAll(String.valueOf(needle), ""); // Abdul Rhmn Sherzd "Abdul Rhmn Sherzd".length() // 17 Return 20 – 17 = 3 // Thus, letter 'a' appears 3 times in "Abdul Rahman Sherzad". Abdul Rahman Sherzad Page 9 of 11
  • 10. https://www.facebook. com/Oxus20 3. Write a method called sumRange that accepts two integers as parameters that represent a range. Print an error message and return zero if the second parameter is less than the first. Otherwise, the method should return the sum of the integers in that range (both first and second parameters are inclusive). public static int sumRange(int start, int end) { int sum = 0; if (end < start) { System.err.println("ERROR: Invalid Rangen"); } else { for (int num = start; num <= end; num++) { sum = sum + num; } } return sum; } 4. Write a method called isAlpha that accepts a String as parameter and returns true if the given String contains only either uppercase or lowercase alphabetic letters. Method1: Using Regular Expression public static boolean isAlpha(String input) { if (input == null || input.length() == 0) return false; if (input.matches("[a-zA-Z]+")) return true; return false; } Method2: Using for loop public static boolean isAlpha(String input) { if (input == null || input.length() == 0) return false; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (!((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'))) { return false; } } return true; } Note: similar functionality is provided by the Character.isLetter(c) method as follow: if (!Character.isLetter(c)) { return false; } Abdul Rahman Sherzad OX US20 Page 10 of 11
  • 11. https://www.facebook. com/Oxus20 Society is the premier Computer society Science professionals and founded of IT in March 2013. The society's goal is to provide information and assistance to Computer Science professionals, increase their job performance and overall agency function by providing cost effective products, services and educational opportunities. So the society believes with the education of Computer Science and IT they can help their nation to higher standards of living. Follow us on Facebook, https://www.facebook.com/Oxus20 Abdul Rahman Sherzad Page 11 of 11