SlideShare una empresa de Scribd logo
1 de 6
Descargar para leer sin conexión
https://www.facebook. com/Oxus20
PART I – Scenario to program and code :
1. Write a method that accept a String named "strInput" as a parameter and returns
every other character of that String parameter starting with the first character.

Method I:- Using Loop
public static String everyOther(String strInput) {
String output = "";
for (int index = 0; index < strInput.length(); index += 2) {
output += strInput.charAt(index);
}
return output;
}

Tips:
 Each and every characters of the given String parameter needs to be scanned and

processed. Therefore, we need to know the number of characters in the String.
strInput.length();
st

1

character is needed that is why int index = 0; we don't need the 2nd character that
is why we incremented index by 2 as follow: index += 2

 strInput.charAt(index); reading the actual character and concatenated to the output

variable.
 Finally

System.out.println( everyOther("SshHeErRzZaAdD") ); // will print Sherzad

Method II:- Using Regular Expression
public static String everyOther(String strInput) {
return strInput.replaceAll("(.)(.)", "$1");
}

Tips:
 In Regular Expression

. matches any character

 In Regular Expression

() use for grouping

 strInput.replaceAll("(.)(.)",

"$1"); // in the expression (.)(.), there are

two groups and each group matches any character; then, in the replacement string,
we can refer to the text of group 1 with the expression $1. Therefore, every other
character will be returned as follow:
System.out.println( everyOther("SshHeErRzZaAdD") ); // will print Sherzad

Abdul Rahman Sherzad

Page 1 of 6
https://www.facebook. com/Oxus20
2. Write a method named reverseString that accepts a String parameter and returns the
reverse of the given String parameter.

Method I:- Using Loop
public static String reverseString(String strInput) {
String output = "";
for (int index = (strInput.length() - 1); index >= 0; index--) {
output += strInput.charAt(index);
}
return output;
}

Tips:
 Each and every characters of the given String parameter needs to be scanned and

processed. Therefore, we need to know the number of characters in the String.
strInput.length();
 Since index ranges from 0 to strInput.length() - 1; that is why we read each and every

character from the end int index = (strInput.length() - 1);
 Finally System.out.println( reverseString("02SUXO") ); // will print OXUS20

Method II:- Using reverse() method of StringBuilder / StringBuffer class
public static String reverseString(String strInput) {
if ((strInput == null) || (strInput.length() <= 1)) {
return strInput;
}
return new StringBuffer(strInput).reverse().toString();
}

Tips:
 Both StringBuilder and StringBuffer class have a reverse method. They work pretty much

the same, except that methods in StringBuilder are not synchronized.

Method III:- Using substring() and Recursion
public static String reverseString(String strInput) {
if ( strInput.equals("") )
return "";
return reverseString(strInput.substring(1)) + strInput.substring(0, 1);
}
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)

Abdul Rahman Sherzad

Page 2 of 6
https://www.facebook. com/Oxus20
3. Write a method to generate a random number in a specific range. For instance, if
the given range is 15 - 25, meaning that 15 is the smallest possible value the
random number can take, and 25 is the biggest. Any other number in between these
numbers is possible to be a value, too.

Method I:- Using Random class of java.util package
public static int rangeInt(int min, int max) {
java.util.Random rand = new java.util.Random();
int randomOutput = rand.nextInt((max - min) + 1) + min;
return randomOutput;
}

Tips:
 The nextInt(int n) method is used to get an int value between 0 (inclusive) and the

specified value (exclusive).
 Consider min = 15, max = 25, then

o rand.nextInt(max - min) // return a random int between 0 (inclusive) and 10
(exclusive). Interval demonstration [0, 10)
o rand.nextInt((max - min) + 1) // return a random int 0 and 10 both inclusive
o rand.nextInt((max

- min) + 1) + min // return a random int 0 and 10

both inclusive + 15;


if the return random int is 0 then 0 + 15 will be 15;



if the return random int is 10 then 10 + 15 will be 25;



if the return random int is 5 then 5 + 15 will be 20;



Hence the return random int will be between min and max value both
inclusive.

Method II:- Using Math.random() method
public static int rangeInt(int min, int max) {
return (int) ( Math.random() * ( (max – min) + 1 ) ) + min;
}

Note:
 In practice, the Random class is often preferable

to Math.random().

Abdul Rahman Sherzad

Page 3 of 6
https://www.facebook. com/Oxus20
PART II – Single Choice and Multiple Choice s:
1. Which of the following declarations is correct?

 [A] boolean b = TRUE;
 [B] byte b = 255;

[A] boolean b = TRUE; // JAVA is Case Sensitive!

 [C] String s = "null";

[B] byte b = 255; // Out of range MIN_VALUE = -128 and
MAX_VALUE = 127

 [D] int i = new Integer("56");

[C] String s = "null"; // Everything between double quotes ""
considered as String
[D] int i = new Integer("56"); // The string "56" is converted
to an int value.

2. Consider the following program:
import oxus20Library.*;
public class OXUS20 {
public static void main(String[] args) {
// The code goes here ...
}
}

What is the name of the java file containing this program?
 A. oxus20Library.java
 B. OXUS20.java

 Each JAVA source file can contain only one
public class.

 C. OXUS20

 The source file's name has to be the name of
that public class. By convention, the

 D. OXUS20.class

source file uses a .java filename extension

 E. Any file name with the java suffix is accepted

3. Consider the following code snippet
public class OXUS20 {
public static void main(String[] args) {
String river = new String("OXUS means Amu Darya");
System.out.println(river.length());
}
}

What is printed?
 A. 17

 B. OXUS means Amu Darya

Abdul Rahman Sherzad

 C. 20

 E. river

Page 4 of 6
https://www.facebook. com/Oxus20
4. A constructor

 A. must have the same name as the class it is declared within.
 B. is used to create objects.
 C. may be declared private
 D. All the above

 A.

A c o n s t r u c t o r m u s t h a v e t h e s a m e n a m e a s t h e c l a s s i t i s d ec l a r ed w i t h i n .
public class OXUS20 {
public OXUS20() {
}
}

 B.

C o n s t r u c t o r i s u s ed t o c r e a t e o b j e c t s
OXUS20 amu_darya = new OXUS20();

 C.

C o n s t r u c t o r m a y b e d e c l a r ed p r i v a t e // private constructor is off
course to restrict instantiation of the class. Actually a good
use of private constructor is in Singleton Pattern.

5. Which of the following may be part of a class definition?

 A. instance variables
 B. instance methods
Following is a sample of class declaration:

 C. constructors
 D. All of the above

class MyClass {
 Field // class variables or instance variables

 E. None of the above
 constructor, and // class constructor or overloaded constructors

 method declarations // class methods or instance methods

}

Abdul Rahman Sherzad

Page 5 of 6
https://www.facebook. com/Oxus20

is a
nonprofit society with the
aim of changing education for
the better by providing
education and assistance to
Computer Science and IT
professionals.

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 6 of 6

Más contenido relacionado

Más de Abdul 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
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesAbdul Rahman Sherzad
 

Más de Abdul Rahman Sherzad (20)

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
 
Java Unicode with Live GUI Examples
Java Unicode with Live GUI ExamplesJava Unicode with Live GUI Examples
Java Unicode with Live GUI Examples
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 

Último

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 

Último (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 

OXUS20 JAVA Programming Questions and Answers PART III

  • 1. https://www.facebook. com/Oxus20 PART I – Scenario to program and code : 1. Write a method that accept a String named "strInput" as a parameter and returns every other character of that String parameter starting with the first character. Method I:- Using Loop public static String everyOther(String strInput) { String output = ""; for (int index = 0; index < strInput.length(); index += 2) { output += strInput.charAt(index); } return output; } Tips:  Each and every characters of the given String parameter needs to be scanned and processed. Therefore, we need to know the number of characters in the String. strInput.length(); st 1 character is needed that is why int index = 0; we don't need the 2nd character that is why we incremented index by 2 as follow: index += 2  strInput.charAt(index); reading the actual character and concatenated to the output variable.  Finally System.out.println( everyOther("SshHeErRzZaAdD") ); // will print Sherzad Method II:- Using Regular Expression public static String everyOther(String strInput) { return strInput.replaceAll("(.)(.)", "$1"); } Tips:  In Regular Expression . matches any character  In Regular Expression () use for grouping  strInput.replaceAll("(.)(.)", "$1"); // in the expression (.)(.), there are two groups and each group matches any character; then, in the replacement string, we can refer to the text of group 1 with the expression $1. Therefore, every other character will be returned as follow: System.out.println( everyOther("SshHeErRzZaAdD") ); // will print Sherzad Abdul Rahman Sherzad Page 1 of 6
  • 2. https://www.facebook. com/Oxus20 2. Write a method named reverseString that accepts a String parameter and returns the reverse of the given String parameter. Method I:- Using Loop public static String reverseString(String strInput) { String output = ""; for (int index = (strInput.length() - 1); index >= 0; index--) { output += strInput.charAt(index); } return output; } Tips:  Each and every characters of the given String parameter needs to be scanned and processed. Therefore, we need to know the number of characters in the String. strInput.length();  Since index ranges from 0 to strInput.length() - 1; that is why we read each and every character from the end int index = (strInput.length() - 1);  Finally System.out.println( reverseString("02SUXO") ); // will print OXUS20 Method II:- Using reverse() method of StringBuilder / StringBuffer class public static String reverseString(String strInput) { if ((strInput == null) || (strInput.length() <= 1)) { return strInput; } return new StringBuffer(strInput).reverse().toString(); } Tips:  Both StringBuilder and StringBuffer class have a reverse method. They work pretty much the same, except that methods in StringBuilder are not synchronized. Method III:- Using substring() and Recursion public static String reverseString(String strInput) { if ( strInput.equals("") ) return ""; return reverseString(strInput.substring(1)) + strInput.substring(0, 1); } public String substring(int beginIndex) public String substring(int beginIndex, int endIndex) Abdul Rahman Sherzad Page 2 of 6
  • 3. https://www.facebook. com/Oxus20 3. Write a method to generate a random number in a specific range. For instance, if the given range is 15 - 25, meaning that 15 is the smallest possible value the random number can take, and 25 is the biggest. Any other number in between these numbers is possible to be a value, too. Method I:- Using Random class of java.util package public static int rangeInt(int min, int max) { java.util.Random rand = new java.util.Random(); int randomOutput = rand.nextInt((max - min) + 1) + min; return randomOutput; } Tips:  The nextInt(int n) method is used to get an int value between 0 (inclusive) and the specified value (exclusive).  Consider min = 15, max = 25, then o rand.nextInt(max - min) // return a random int between 0 (inclusive) and 10 (exclusive). Interval demonstration [0, 10) o rand.nextInt((max - min) + 1) // return a random int 0 and 10 both inclusive o rand.nextInt((max - min) + 1) + min // return a random int 0 and 10 both inclusive + 15;  if the return random int is 0 then 0 + 15 will be 15;  if the return random int is 10 then 10 + 15 will be 25;  if the return random int is 5 then 5 + 15 will be 20;  Hence the return random int will be between min and max value both inclusive. Method II:- Using Math.random() method public static int rangeInt(int min, int max) { return (int) ( Math.random() * ( (max – min) + 1 ) ) + min; } Note:  In practice, the Random class is often preferable to Math.random(). Abdul Rahman Sherzad Page 3 of 6
  • 4. https://www.facebook. com/Oxus20 PART II – Single Choice and Multiple Choice s: 1. Which of the following declarations is correct?  [A] boolean b = TRUE;  [B] byte b = 255; [A] boolean b = TRUE; // JAVA is Case Sensitive!  [C] String s = "null"; [B] byte b = 255; // Out of range MIN_VALUE = -128 and MAX_VALUE = 127  [D] int i = new Integer("56"); [C] String s = "null"; // Everything between double quotes "" considered as String [D] int i = new Integer("56"); // The string "56" is converted to an int value. 2. Consider the following program: import oxus20Library.*; public class OXUS20 { public static void main(String[] args) { // The code goes here ... } } What is the name of the java file containing this program?  A. oxus20Library.java  B. OXUS20.java  Each JAVA source file can contain only one public class.  C. OXUS20  The source file's name has to be the name of that public class. By convention, the  D. OXUS20.class source file uses a .java filename extension  E. Any file name with the java suffix is accepted 3. Consider the following code snippet public class OXUS20 { public static void main(String[] args) { String river = new String("OXUS means Amu Darya"); System.out.println(river.length()); } } What is printed?  A. 17  B. OXUS means Amu Darya Abdul Rahman Sherzad  C. 20  E. river Page 4 of 6
  • 5. https://www.facebook. com/Oxus20 4. A constructor  A. must have the same name as the class it is declared within.  B. is used to create objects.  C. may be declared private  D. All the above  A. A c o n s t r u c t o r m u s t h a v e t h e s a m e n a m e a s t h e c l a s s i t i s d ec l a r ed w i t h i n . public class OXUS20 { public OXUS20() { } }  B. C o n s t r u c t o r i s u s ed t o c r e a t e o b j e c t s OXUS20 amu_darya = new OXUS20();  C. C o n s t r u c t o r m a y b e d e c l a r ed p r i v a t e // private constructor is off course to restrict instantiation of the class. Actually a good use of private constructor is in Singleton Pattern. 5. Which of the following may be part of a class definition?  A. instance variables  B. instance methods Following is a sample of class declaration:  C. constructors  D. All of the above class MyClass {  Field // class variables or instance variables  E. None of the above  constructor, and // class constructor or overloaded constructors  method declarations // class methods or instance methods } Abdul Rahman Sherzad Page 5 of 6
  • 6. https://www.facebook. com/Oxus20 is a nonprofit society with the aim of changing education for the better by providing education and assistance to Computer Science and IT professionals. 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 6 of 6