SlideShare uma empresa Scribd logo
1 de 11
Baixar para ler offline
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 10
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 10
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 10
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 10
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 10
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 10
https://www.facebook. com/Oxus20

3. 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

4. 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 10
https://www.facebook. com/Oxus20

PART III – Write the program for the followings :
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 10
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 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

Page 10 of 10
‫‪OXUS20 is a non-profit society with the aim of changing education for‬‬
‫‪the better by providing education and assistance to IT and computer‬‬
‫.‪science professionals‬‬

‫آکسیوس20 یک انجمن غیر انتفاعی با هدف تغییرو تقویت آموزش و پرورش از طریق ارائه آموزش و کمک به‬
‫متخصصان علوم کامپیوتر است.‬
‫نام این انجمن برگرفته از دریای آمو پر آب ترین رود آسیای میانه که دست موج آن بیانگر استعداد های نهفته این انجمن بوده، و این دریا از‬
‫دامنه های کهن پامیر سرچشمه گرفته و ماورای شمالی سرزمین باستانی افغانستان را آبیاری میکند که این حالت دریا هدف ارایه خدمات‬
‫انجمن را انعکاس میدهد.‬
‫آکسیوس20 در نظر دارد تا خدماتی مانند ایجاد فضای مناسب برای تجلی استعدادها و برانگیختن خالقیت و شکوفایی علمی محصالن و دانش‬
‫پژوهان، نهادمند ساختن فعالیت های فوق برنامه علمی و کاربردی، شناسایی افراد خالق، نخبه و عالقمند و بهره گیری از مشارکت آنها در‬
‫ارتقای فضای علمی پوهنتون ها و دیگر مراکز آموزشی و جامعه همچون تولید و انتشار نشریات علمی تخصصی علوم عصری و تکنالوژی‬
‫معلوماتی را به شکل موثر آن در جامعه در راستای هرچه بهتر شدن زمینه تدریس، تحقیق و پژوهش و راه های رسیدن به آمال افراد جامعه‬
‫را فراهم میسازد.‬

‫,‪Follow us on Facebook‬‬
‫02‪https://www.facebook.com/Oxus‬‬

Mais conteúdo relacionado

Mais de OXUS 20

Everything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsEverything about Database JOINS and Relationships
Everything about Database JOINS and RelationshipsOXUS 20
 
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 StepOXUS 20
 
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 JavaOXUS 20
 
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 TechnologiesOXUS 20
 
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 ClassesOXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART IIIOXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART IIOXUS 20
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART IOXUS 20
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART IIOXUS 20
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART IOXUS 20
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number TutorialOXUS 20
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIOXUS 20
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesOXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticOXUS 20
 

Mais de OXUS 20 (15)

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
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
JAVA GUI PART III
JAVA GUI PART IIIJAVA GUI PART III
JAVA GUI PART III
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Java GUI PART II
Java GUI PART IIJava GUI PART II
Java GUI PART II
 
JAVA GUI PART I
JAVA GUI PART IJAVA GUI PART I
JAVA GUI PART I
 
Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
JAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART IIIJAVA Programming Questions and Answers PART III
JAVA Programming Questions and Answers PART III
 
Object Oriented Programming with Real World Examples
Object Oriented Programming with Real World ExamplesObject Oriented Programming with Real World Examples
Object Oriented Programming with Real World Examples
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 

Último

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxCarlos105
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYKayeClaireEstoconing
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 

Último (20)

How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptxBarangay Council for the Protection of Children (BCPC) Orientation.pptx
Barangay Council for the Protection of Children (BCPC) Orientation.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITYISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
ISYU TUNGKOL SA SEKSWLADIDA (ISSUE ABOUT SEXUALITY
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 

JAVA Programming Questions and Answers PART I By OXUS20

  • 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 10
  • 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 10
  • 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 10
  • 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 10
  • 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 10
  • 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 10
  • 7. https://www.facebook. com/Oxus20 3. 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 4. 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 10
  • 8. https://www.facebook. com/Oxus20 PART III – Write the program for the followings : 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 10
  • 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 10
  • 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 Page 10 of 10
  • 11. ‫‪OXUS20 is a non-profit society with the aim of changing education for‬‬ ‫‪the better by providing education and assistance to IT and computer‬‬ ‫.‪science professionals‬‬ ‫آکسیوس20 یک انجمن غیر انتفاعی با هدف تغییرو تقویت آموزش و پرورش از طریق ارائه آموزش و کمک به‬ ‫متخصصان علوم کامپیوتر است.‬ ‫نام این انجمن برگرفته از دریای آمو پر آب ترین رود آسیای میانه که دست موج آن بیانگر استعداد های نهفته این انجمن بوده، و این دریا از‬ ‫دامنه های کهن پامیر سرچشمه گرفته و ماورای شمالی سرزمین باستانی افغانستان را آبیاری میکند که این حالت دریا هدف ارایه خدمات‬ ‫انجمن را انعکاس میدهد.‬ ‫آکسیوس20 در نظر دارد تا خدماتی مانند ایجاد فضای مناسب برای تجلی استعدادها و برانگیختن خالقیت و شکوفایی علمی محصالن و دانش‬ ‫پژوهان، نهادمند ساختن فعالیت های فوق برنامه علمی و کاربردی، شناسایی افراد خالق، نخبه و عالقمند و بهره گیری از مشارکت آنها در‬ ‫ارتقای فضای علمی پوهنتون ها و دیگر مراکز آموزشی و جامعه همچون تولید و انتشار نشریات علمی تخصصی علوم عصری و تکنالوژی‬ ‫معلوماتی را به شکل موثر آن در جامعه در راستای هرچه بهتر شدن زمینه تدریس، تحقیق و پژوهش و راه های رسیدن به آمال افراد جامعه‬ ‫را فراهم میسازد.‬ ‫,‪Follow us on Facebook‬‬ ‫02‪https://www.facebook.com/Oxus‬‬