The document contains 20 multiple choice questions about Java programming concepts such as threads, assertions, references, operators, and more. For each question, the stem presents a code snippet, output, or statement and asks which answer choice is true. The explanations provided give detailed reasoning for the correct answers and why the incorrect choices are wrong based on Java specifications.
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
Assess your preparation with these Practice Test Questions with Explanation. Questions are Extracted from Highest Rated Course on Udemy which has helped a lot of students to pass the exam with good score.
500+ multiple choice questions with explanation to assess Oracle Certified Associate, Java SE 8 Programmer II preparation.
Highest Rated course on UDEMY
Read the students success stories at:
https://udayankhattry.com/ocp/
Enroll now to receive maximum discount on the course ie. for just $9.99 or ₹640.00, click the link below- https://www.udemy.com/java-ocp/?couponCode=UDAYANKHATTRY.COM
To avail maximum discount on all courses visit: www.udayankhattry.com
Here we are going to learn why is a good practice to use interfaces and how they are different from abstraction classes. Further more we are going to see how which one of them to use.
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
Here we are going to take a look how to use for loop, foreach loop and while loop. Also we are going to learn how to use and invoke methods and how to define classes in Java programming language.
Oracle Certified Associate (OCA) Java SE 8 Programmer II (1Z0-809) - Practice...Udayan Khattry
Assess your preparation with these Practice Test Questions with Explanation. Questions are Extracted from Highest Rated Course on Udemy which has helped a lot of students to pass the exam with good score.
500+ multiple choice questions with explanation to assess Oracle Certified Associate, Java SE 8 Programmer II preparation.
Highest Rated course on UDEMY
Read the students success stories at:
https://udayankhattry.com/ocp/
Enroll now to receive maximum discount on the course ie. for just $9.99 or ₹640.00, click the link below- https://www.udemy.com/java-ocp/?couponCode=UDAYANKHATTRY.COM
To avail maximum discount on all courses visit: www.udayankhattry.com
Here we are going to learn why is a good practice to use interfaces and how they are different from abstraction classes. Further more we are going to see how which one of them to use.
In this chapter we will get familiar with primitive types and variables in Java – what they are and how to work with them. First we will consider the data types – integer types, real types with floating-point, Boolean, character, string and object type. We will continue with the variables, with their characteristics, how to declare them, how they are assigned a value and what is variable initialization.
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
In this chapter we will get acquainted with the operators in Java and the actions they can perform on the different data types. We will explain the priorities of the operators and we will analyze the different types of operators, according to the count of the arguments they can take and the actions they can perform. In the second part we will examine the conversion of data types.
Here we are going to take a look how to use for loop, foreach loop and while loop. Also we are going to learn how to use and invoke methods and how to define classes in Java programming language.
19. Data Structures and Algorithm ComplexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use. We will explain how to choose between data structures like hash-tables, arrays, dynamic arrays and sets implemented by hash-tables or balanced trees. Almost all of these structures are implemented as part of NET Framework, so to be able to write efficient and reliable code we have to learn to apply the most appropriate structures for each situation.
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
In this chapter we will understand how to define custom classes and their elements. We will learn to declare fields, constructors and properties for the classes. We will revise what a method is and we will broaden our knowledge about access modifiers and methods.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
In this lesson you will learn how to use basic syntax, conditions, if-else statements and loops (for-loop, while-loop and do-while-loop) in Java and how to use the debugger.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-basic-syntax-conditions-and-loops
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
100% Accurate and Updated dumps available for 1Z0-804 Exam-Java SE 7 Programmer II get 20% off on all dumps visit@https://www.troytec.com/1Z0-804-exams.html
19. Data Structures and Algorithm ComplexityIntro C# Book
In this chapter we will compare the data structures we have learned so far by the performance (execution speed) of the basic operations (addition, search, deletion, etc.). We will give specific tips in what situations what data structures to use. We will explain how to choose between data structures like hash-tables, arrays, dynamic arrays and sets implemented by hash-tables or balanced trees. Almost all of these structures are implemented as part of NET Framework, so to be able to write efficient and reliable code we have to learn to apply the most appropriate structures for each situation.
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
In this chapter we will get more familiar with what methods are and why we need to use them. The reader will be shown how to declare methods, what parameters are and what a method’s signature is, how to call a method, how to pass arguments of methods and how methods return values. At the end of this chapter we will know how to create our own method and how to use (invoke) it whenever necessary. Eventually, we will suggest some good practices in working with methods. The content of this chapter accompanied by detailed examples and exercises that will help the reader practice the learned material.
In this chapter we will understand how to define custom classes and their elements. We will learn to declare fields, constructors and properties for the classes. We will revise what a method is and we will broaden our knowledge about access modifiers and methods.
Learn about how to define and invoke methods in Java, how to use parameters and return results. Watch the video lesson here:
https://softuni.org/code-lessons/java-foundations-certification-methods
In this lesson you will learn how to use basic syntax, conditions, if-else statements and loops (for-loop, while-loop and do-while-loop) in Java and how to use the debugger.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-basic-syntax-conditions-and-loops
In this chapter we will learn about arrays as a way to work with sequences of elements of the same type. We will explain what arrays are, how we declare, create, instantiate and use them. We will examine one-dimensional and multidimensional arrays. We will learn different ways to iterate through the array, read from the standard input and write to the standard output. We will give many example exercises, which can be solved using arrays and we will show how useful they really are.
100% Accurate and Updated dumps available for 1Z0-804 Exam-Java SE 7 Programmer II get 20% off on all dumps visit@https://www.troytec.com/1Z0-804-exams.html
Consider this code using the ArrayBag of Section 5.2 and the Locat.docxmaxinesmith73660
Consider this code using the ArrayBag of Section 5.2 and the Location class from Chapter 2. What is the output?
Location i = new Location(0, 3);
Location j = new Location(0, 3);
b.add(i);
b.add(j);
System.out.println(b.countOccurrences(i));
A. 0
B. 1
C. 2
D. 3
Suppose that b and c are Integer objects. A typical use of the clone method looks like this:
b = (Integer) c.clone( );
Write a short clear explanation of why the (Integer) type cast is required in this typical example.
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that obj is an Object variable and s is a String variable. Which of the following statements
is a correctly-compiling widening conversion? Don't worry about possible run-time exceptions
A. obj = s;
B. s = obj;
C. s = (String) obj;
D. Two or more answers are correct.
Suppose that x and y are reference variables and a program activates x.equals(y). What occurs if x is the null reference?
A. A NullPointerException occurs
B. It always returns true.
C. It always returns false.
D. It returns true if y is also a null reference; otherwise it returns false.
Consider the implementation of the Stack using a partially-filled array.
What goes wrong if we try to store the top of the Stack at location [0] and the bottom of the Stack at the last used position of the array?
A. Both peek and pop would require linear time.
B. Both push and pop would require linear time.
C. The Stack could not be used to check balanced parentheses.
D. The Stack could not be used to evaluate postfix expressions.
Write some lines of code that declares an Integer object, using the Integer wrapper class.
Assign the value 42 to this object, then copy this value from the Integer object to an ordinary int variable.
Consider the usual algorithm for determining whether a sequence of parentheses is balanced.
What is the maximum number of parentheses that will appear on the stack AT ANY ONE TIME when the algorithm analyzes: (()(())(()))?
A. 1
B. 2
C. 3
D. 4
E. 5 or more
Consider the usual algorithm to convert an infix expression to a postfix expression.
Suppose that you have read 10 input characters during a conversion and that the
stack now contains the symbols as shown below. Suppose that you read and process
the 11th symbol of the input. What symbol is at the top of the stack in the case where
the 11th symbol is each of the choices shown?
Which of the following stack operations could result in stack underflow?
Answer
A. is_empty
B. pop
C. push
D. Two or more of the above answers
What is the value of the postfix expression 6 3 2 4 + - *:
Answer
A. Something between -15 and -100
B. Something between -5 and -15
C. Something between 5 and -5
D. Something between 5 and 15
E. Something between 15 and 100
1. An array o.
1 Midterm Preview Time allotted 50 minutes CS 11.docxhoney725342
1
Midterm Preview
Time allotted: 50 minutes
CS 110, Programming Fundamentals I
Central Washington University
Computer Science
Instructions
There are five sections on this exam that contain 24 required questions, a sixth section that contains extra
credit questions, and a last, seventh section, with supplementary information that may be helpful in answering
some of the required questions. This midterm is worth 100 points. Each question in a section is worth the points
indicated at the beginning of the section.
• Pace yourself
• Do not spend too much time on any one question
• Partial credit will be given, if warranted
• Partial credit will NOT be given on the extra credit questions, and points will NOT be taken off for
incorrectly answering an extra credit question
This exam is a closed book, closed notes, no IPhones, no Internet, etc. exam. All that you need is a pen or
pencil.
Name (Print)
Honor Code Statement: I pledge that this submission is solely my work, and that I have neither
given to, nor received help from anyone.
Signature:
Section Question Type Question Numbers Points Possible Points Scored
I True / False 1-10 20
II Multiple Choice 11-15 20
III Find the Error 16 20
IV Short Answer 17-22 30
V One or More Answers 23-24 10
Total 100
VI Extra Credit
Total Including Extra Credit
2
Section I: True/False Each question is worth 2 points; no partial credit given
Circle either True or False.
1. True / False The following is a syntactically correct variable declaration and assignment
statement:
double int = 2.0;
2.
True / False
The diagram in Figure 1a is the decision structure logic of the Java statements in
Figure 1b.
if (Condition_1){
if (Condition_2){
Statement_B;
}else{
Statement_C;
}
}
if (! Condition_1){
Statement_A;
}
Figure 1a Figure 1b
3. True / False Java is a case sensitive programming language.
4. True / False Assuming that letter has been declared as a variable of type char, the below
statement is syntactically correct:
letter = “a”;
5. True / False For the logical AND operator, &&, which connects two boolean expressions, both
expressions must be false for the overall expression to be false.
6. True / False The below two pieces of code output the same thing to the console:
int someVariable = 0;
System.out.println(“Output : “ + someVariable);
int someVar1 = 1, someVar2 = 2;
System.out.println(“Output : “ + someVar1 / someVar2);
7. True / False Syntax errors are mistakes that the programmer has made that violate the rules of the
programming language.
3
8. True / False The following Java code is syntactically incorrect:
Scanner keyBoard = new Scanner(System.in);
int someValue = keyBoard.nextInt();
switch (someValue){
case 1:
case 2:
case 3:
System.out.println("Input is 1 or 2 or 3.");
break;
default:
Syst ...
Name _______________________________ Class time __________.docxrosemarybdodson23141
Name: _______________________________ Class time: __________
Prewriting Instructions for Paper 2 (Final Paper due 4/22)
1. Your choices for Paper 2 are posted on blackboard and also listed below.
2. Choose 1 of these paper options. Notice that each choice also mentions the type of paper (comparison, etc.) My paper choice is: _________________________: paper type: _______________.
3. Read the related essay(s) in your Research and Composition textbook.
4. Thursday: write a tentative thesis for paper 2 (one sentence): ______________________________________________________________________________________________________________________________________________________________________________________________________________________.
5. Thursday: write 5 questions that you will need to answer through research to write this paper (for ex. What is the divorce rate for 2012?) Write legibly please.
1.
2.
3.
4.
5.
6. Thursday: go to the library and use the databases to locate at least three sources that will likely give you the information to answer the five questions above. At least one should be a book, at least one should be a database article. In addition, you may use your textbook, internet, or even refer to a film. Write down the all of the information about each source. You will need this information for a works cited page later or to locate the article and book again. You do not need to answer the questions right away, but if you do find the answers, take notes or make a copy of the source.
Source 1: ____________________________________________________________________________________________________________________________________________________________
Source 2: ____________________________________________________________________________________________________________________________________________________________
Source 3: ____________________________________________________________________________________________________________________________________________________________
7. Have any new questions come to mind? What are they? Write them here:
8. Have you revised your thesis? What is it? ___________________________________
_____________________________________________________________________.
9. Write a tentative first paragraph to paper 2 (this includes your thesis):
10. Turn this in Tuesday 3/25 in exchange for your last Q exercise, M&M Color Distribution.
***You need this prewriting exercise completed to receive your instructions and data for this last Q exercise and parts of this exercise will count for your attendance in a week or so.
See next page
Writing Assignment 2 Choices due on or before 4/22
Here are your choices for Writing Assignment 2 due 4/22. Additional research is required for all choices. Two visuals, tables or figures, are required. Your paper will be in MLA format with a works cited page. This paper is approximately 5 pages including a works cited page.
1. Read the essays in Chapter 8. Go .
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
GSP 125 Become Exceptional/newtonhelp.combellflower148
For more course tutorials visit
www.newtonhelp.com
Question 1. 1. In addition to grouping functions together, a class also groups (Points : 3)
libraries.
math operations.
print statements.
variables.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
1
1. 1.class X implements Runnable
{
public static void main(String args[])
{
/* Missing code? */
}
public void run() {}
}
Which of the following line of code is suitable to start a thread ?
A.Thread t = new Thread(X);
B.Thread t = new Thread(X); t.start();
C.X run = new X(); Thread t = new Thread(run); t.start();
D.Thread t = new Thread(); x.run();
Answer: Option C
Explanation:
Option C is suitable to start a thread.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
2.What will be the output of the program?
public class WaitTest
{
public static void main(String [] args)
{
System.out.print("1 ");
synchronized(args)
{
System.out.print("2 ");
try
{
args.wait(); /* Line 11 */
}
catch(InterruptedException e){ }
}
System.out.print("3 ");
}
}
A.
It fails to compile because the IllegalMonitorStateException of wait() is not dealt with in
line 11.
B.1 2 3
C.1 3
D.1 2
2. Answer: Option D
Explanation:
1 and 2 will be printed, but there will be no return from the wait call because no other thread
will notify the main thread, so 3 will never be printed. The program is essentially frozen at line
11.
A is incorrect; IllegalMonitorStateException is an unchecked exception so it doesn't have to be
dealt with explicitly.
B and C are incorrect; 3 will never be printed, since this program will never terminate because
it will wait forever.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
3.In the given program, how many lines of output will be produced?
public class Test
{
public static void main(String [] args)
{
int [] [] [] x = new int [3] [] [];
int i, j;
x[0] = new int[4][];
x[1] = new int[2][];
x[2] = new int[5][];
for (i = 0; i < x.length; i++)
{
for (j = 0; j < x[i].length; j++)
{
x[i][j] = new int [i + j + 1];
System.out.println("size = " + x[i][j].length);
}
}
}
}
A.7 B.9
C.11 D.13
E.Compilation fails
Answer: Option C
Explanation:
The loops use the array sizes (length).
3. It produces 11 lines of output as given below.
D:Java>javac Test.java
D:Java>java Test
size = 1
size = 2
size = 3
size = 4
size = 2
size = 3
size = 3
size = 4
size = 5
size = 6
size = 7
Therefore, 11 is the answer.
Learn more problems on : Language Fundamentals
Discuss about this problem : Discuss in Forum
4.What two statements are true about the result obtained from calling Math.random()?
1. The result is less than 0.0.
2. The result is greater than or equal to 0.0..
3. The result is less than 1.0.
4. The result is greater than 1.0.
5. The result is greater than or equal to 1.0.
A.1 and 2
B.2 and 3
C.3 and 4
D.4 and 5
Answer: Option B
Explanation:
(1) and (2) are correct. The result range for random() is 0.0 to < 1.0; 1.0 is not in range.
Learn more problems on : Java.lang Class
Discuss about this problem : Discuss in Forum
5.public void test(int x)
{
int odd = 1;
if(odd) /* Line 4 */
4. {
System.out.println("odd");
}
else
{
System.out.println("even");
}
}
Which statement is true?
A.Compilation fails.
B."odd" will always be output.
C."even" will always be output.
D."odd" will be output for odd values of x, and "even" for even values.
Answer: Option A
Explanation:
The compiler will complain because of incompatible types (line 4), the if expects a boolean but
it gets an integer.
Learn more problems on : Flow Control
Discuss about this problem : Discuss in Forum
6.Which of the following are Java reserved words?
1. run
2. import
3. default
4. implement
A.1 and 2 B.2 and 3
C.3 and 4 D.2 and 4
Answer: Option B
Explanation:
(2) - This is a Java keyword
(3) - This is a Java keyword
(1) - Is incorrect because although it is a method of Thread/Runnable it is not a keyword
(4) - This is not a Java keyword the keyword is implements
5. Learn more problems on : Objects and Collections
Discuss about this problem : Discuss in Forum
7./* Missing Statement ? */
public class foo
{
public static void main(String[]args)throws Exception
{
java.io.PrintWriter out = new java.io.PrintWriter();
new java.io.OutputStreamWriter(System.out,true);
out.println("Hello");
}
}
What line of code should replace the missing statement to make this program compile?
A.No statement required.
B.import java.io.*;
C.include java.io.*;
D.import java.io.PrintWriter;
Answer: Option A
Explanation:
The usual method for using/importing the java packages/classes is by using an import
statement at the top of your code. However it is possible to explicitly import the specific class
that you want to use as you use it which is shown in the code above. The disadvantage of this
however is that every time you create a new object you will have to use the class path in the
case "java.io" then the class name in the long run leading to a lot more typing.
Learn more problems on : Objects and Collections
Discuss about this problem : Discuss in Forum
8.What will be the output of the program?
public class Test
{
private static float[] f = new float[2];
public static void main (String[] args)
{
System.out.println("f[0] = " + f[0]);
}
}
A.f[0] = 0 B.f[0] = 0.0
C.Compile Error D.Runtime Exception
Answer: Option B
6. Explanation:
The choices are between Option A and B, what this question is really testing is your knowledge
of default values of an initialized array. This is an array type float i.e. it is a type that uses
decimal point numbers therefore its initial value will be 0.0 and not 0
Learn more problems on : Objects and Collections
Discuss about this problem : Discuss in Forum
9.What will be the output of the program?
int x = 3;
int y = 1;
if (x = y) /* Line 3 */
{
System.out.println("x =" + x);
}
A.x = 1
B.x = 3
C.Compilation fails.
D.The code runs with no output.
Answer: Option C
Explanation:
Line 3 uses an assignment as opposed to comparison. Because of this, the if statement receives
an integer value instead of a boolean. And so the compilation fails.
Learn more problems on : Flow Control
Discuss about this problem : Discuss in Forum
10.class Bar { }
class Test
{
Bar doBar()
{
Bar b = new Bar(); /* Line 6 */
return b; /* Line 7 */
}
public static void main (String args[])
{
Test t = new Test(); /* Line 11 */
Bar newBar = t.doBar(); /* Line 12 */
System.out.println("newBar");
newBar = new Bar(); /* Line 14 */
System.out.println("finishing"); /* Line 15 */
}
}
7. At what point is the Bar object, created on line 6, eligible for garbage collection?
A.after line 12
B.after line 14
C.after line 7, when doBar() completes
D.after line 15, when main() completes
Answer: Option B
Explanation:
Option B is correct. All references to the Bar object created on line 6 are destroyed when a
new reference to a new Bar object is assigned to the variable newBar on line 14. Therefore
the Bar object, created on line 6, is eligible for garbage collection after line 14.
Option A is wrong. This actually protects the object from garbage collection.
Option C is wrong. Because the reference in the doBar() method is returned on line 7 and is
stored in newBar on line 12. This preserver the object created on line 6.
Option D is wrong. Not applicable because the object is eligible for garbage collection after
line 14.
Learn more problems on : Garbage Collections
Discuss about this problem : Discuss in Forum
11.void start() {
A a = new A();
B b = new B();
a.s(b);
b = null; /* Line 5 */
a = null; /* Line 6 */
System.out.println("start completed"); /* Line 7 */
}
When is the B object, created in line 3, eligible for garbage collection?
A.after line 5
B.after line 6
C.after line 7
D.There is no way to be absolutely certain.
Answer: Option D
Learn more problems on : Garbage Collections
Discuss about this problem : Discuss in Forum
12.What is the numerical range of a char?
8. A.-128 to 127 B.-(215)
to (215
) - 1
C.0 to 32767 D.0 to 65535
Answer: Option D
Explanation:
A char is really a 16-bit integer behind the scenes, so it supports 216
(from 0 to 65535) values.
Learn more problems on : Language Fundamentals
Discuss about this problem : Discuss in Forum
13.Which one of these lists contains only Java programming language keywords?
A.class, if, void, long, Int, continue
B.goto, instanceof, native, finally, default, throws
C.try, virtual, throw, final, volatile, transient
D.strictfp, constant, super, implements, do
E.byte, break, assert, switch, include
Answer: Option B
Explanation:
All the words in option B are among the 49 Java keywords. Although goto reserved as a
keyword in Java, goto is not used and has no function.
Option A is wrong because the keyword for the primitive int starts with a lowercase i.
Option C is wrong because "virtual" is a keyword in C++, but not Java.
Option D is wrong because "constant" is not a keyword. Constants in Java are marked static
and final.
Option E is wrong because "include" is a keyword in C, but not in Java.
Learn more problems on : Language Fundamentals
Discuss about this problem : Discuss in Forum
14.x = 0;
if (x1.hashCode() != x2.hashCode() ) x = x + 1;
if (x3.equals(x4) ) x = x + 10;
if (!x5.equals(x6) ) x = x + 100;
if (x7.hashCode() == x8.hashCode() ) x = x + 1000;
System.out.println("x = " + x);
and assuming that the equals() and hashCode() methods are property implemented, if the
9. output is "x = 1111", which of the following statements will always be true?
A.x2.equals(x1)
B.x3.hashCode() == x4.hashCode()
C.x5.hashCode() != x6.hashCode()
D.x8.equals(x7)
Answer: Option B
Explanation:
By contract, if two objects are equivalent according to the equals() method, then the
hashCode() method must evaluate them to be ==.
Option A is incorrect because if the hashCode() values are not equal, the two objects must not
be equal.
Option C is incorrect because if equals() is not true there is no guarantee of any result from
hashCode().
Option D is incorrect because hashCode() will often return == even if the two objects do not
evaluate to equals() being true.
Learn more problems on : Objects and Collections
Discuss about this problem : Discuss in Forum
15.What will be the output of the program?
public class ExamQuestion6
{
static int x;
boolean catch()
{
x++;
return true;
}
public static void main(String[] args)
{
x=0;
if ((catch() | catch()) || catch())
x++;
System.out.println(x);
}
}
A.1
B.2
C.3
D.Compilation Fails
10. Answer: Option D
Explanation:
Initially this looks like a question about the logical and logical shortcut operators "|" and "||"
but on closer inspection it should be noticed that the name of the boolean method in this code
is "catch". "catch" is a reserved keyword in the Java language and cannot be used as a method
name. Hence Compilation will fail.
Learn more problems on : Java.lang Class
Discuss about this problem : Discuss in Forum
16.public class Test
{
public void foo()
{
assert false; /* Line 5 */
assert false; /* Line 6 */
}
public void bar()
{
while(true)
{
assert false; /* Line 12 */
}
assert false; /* Line 14 */
}
}
What causes compilation to fail?
A.Line 5
B.Line 6
C.Line 12
D.Line 14
Answer: Option D
Explanation:
Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a
compile-time error if a statement cannot be executed because it is unreachable. The question
is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also
be unreachable. The answer must be something other than assert.
Examine the following:
A while statement can complete normally if and only if at least one of the following is true:
11. - The while statement is reachable and the condition expression is not a constant expression
with value true.
-There is a reachable break statement that exits the while statement.
The while statement at line 11 is infinite and there is no break statement therefore line 14 is
unreachable. You can test this with the following code:
public class Test80
{
public void foo()
{
assert false;
assert false;
}
public void bar()
{
while(true)
{
assert false;
break;
}
assert false;
}
}
Learn more problems on : Assertions
Discuss about this problem : Discuss in Forum
17.Which of the following statements is true?
A.
If assertions are compiled into a source file, and if no flags are included at runtime,
assertions will execute by default.
B.As of Java version 1.4, assertion statements are compiled by default.
C.
With the proper use of runtime arguments, it is possible to instruct the VM to disable
assertions for a certain class, and to enable assertions for a certain package, at the same
time.
D.
When evaluating command-line arguments, the VM gives -ea flags precedence over -
da flags.
Answer: Option C
Explanation:
Option C is true because multiple VM flags can be used on a single invocation of a Java
program.
Option A is incorrect because at runtime assertions are ignored by default.
Option B is incorrect because as of Java 1.4 you must add the argument -source 1.4 to the
12. command line if you want the compiler to compile assertion statements.
Option D is incorrect because the VM evaluates all assertion flags left to right.
Learn more problems on : Assertions
Discuss about this problem : Discuss in Forum
18.Which statement is true?
A.The notifyAll() method must be called from a synchronized context.
B.To call wait(), an object must own the lock on the thread.
C.The notify() method is defined in class java.lang.Thread.
D.The notify() method causes a thread to immediately release its locks.
Answer: Option A
Explanation:
Option A is correct because the notifyAll() method (along with wait() and notify()) must
always be called from within a synchronized context.
Option B is incorrect because to call wait(), the thread must own the lock on the object that
wait() is being invoked on, not the other way around.
Option C is wrong because notify() is defined in java.lang.Object.
Option D is wrong because notify() will not cause a thread to release its locks. The thread can
only release its locks by exiting the synchronized code.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
19.import java.awt.Button;
class CompareReference
{
public static void main(String [] args)
{
float f = 42.0f;
float [] f1 = new float[2];
float [] f2 = new float[2];
float [] f3 = f1;
long x = 42;
f1[0] = 42.0f;
}
}
which three statements are true?
1. f1 == f2
13. 2. f1 == f3
3. f2 == f1[1]
4. x == f1[0]
5. f == f1[0]
A.1, 2 and 3 B.2, 4 and 5
C.3, 4 and 5 D.1, 4 and 5
Answer: Option B
Explanation:
(2) is correct because the reference variables f1 and f3 refer to the same array object.
(4) is correct because it is legal to compare integer and floating-point types.
(5) is correct because it is legal to compare a variable with an array element.
(3) is incorrect because f2 is an array object and f1[1] is an array element.
Learn more problems on : Operators and Assignments
Discuss about this problem : Discuss in Forum
20.Which two statements are equivalent?
1. 16*4
2. 16>>2
3. 16/2^2
4. 16>>>2
A.1 and 2 B.2 and 4
C.3 and 4 D.1 and 3
Answer: Option B
Explanation:
(2) is correct. 16 >> 2 = 4
(4) is correct. 16 >>> 2 = 4
(1) is wrong. 16 * 4 = 64
(3) is wrong. 16/2 ^ 2 = 10
14. Learn more problems on : Operators and Assignments
Discuss about this problem : Discuss in Forum
1. What will be the output of the program?
class A
{
final public int GetResult(int a, int b) { return 0; }
}
class B extends A
{
public int GetResult(int a, int b) {return 1; }
}
public class Test
{
public static void main(String args[])
{
B b = new B();
System.out.println("x = " + b.GetResult(0, 1));
}
}
A.x = 0
B.x = 1
C.Compilation fails.
D.An exception is thrown at runtime.
Answer: Option C
Explanation:
The code doesn't compile because the method GetResult() in class A is final and so cannot be
overridden.
Learn more problems on : Declarations and Access Control
Discuss about this problem : Discuss in Forum
2.What will be the output of the program?
class SC2
{
public static void main(String [] args)
{
SC2 s = new SC2();
s.start();
}
void start()
{
int a = 3;
int b = 4;
15. System.out.print(" " + 7 + 2 + " ");
System.out.print(a + b);
System.out.print(" " + a + b + " ");
System.out.print(foo() + a + b + " ");
System.out.println(a + b + foo());
}
String foo()
{
return "foo";
}
}
A.9 7 7 foo 7 7foo
B.72 34 34 foo34 34foo
C.9 7 7 foo34 34foo
D.72 7 34 foo34 7foo
Answer: Option D
Explanation:
Because all of these expressions use the + operator, there is no precedence to worry about and
all of the expressions will be evaluated from left to right. If either operand being evaluated is a
String, the + operator will concatenate the two operands; if both operands are numeric, the +
operator will add the two operands.
Learn more problems on : Operators and Assignments
Discuss about this problem : Discuss in Forum
3.What will be the output of the program?
class BoolArray
{
boolean [] b = new boolean[3];
int count = 0;
void set(boolean [] x, int i)
{
x[i] = true;
++count;
}
public static void main(String [] args)
{
BoolArray ba = new BoolArray();
ba.set(ba.b, 0);
ba.set(ba.b, 2);
ba.test();
}
void test()
16. {
if ( b[0] && b[1] | b[2] )
count++;
if ( b[1] && b[(++count - 2)] )
count += 7;
System.out.println("count = " + count);
}
}
A.count = 0 B.count = 2
C.count = 3 D.count = 4
Answer: Option C
Explanation:
The reference variables b and x both refer to the same boolean array. count is incremented for
each call to the set() method, and once again when the first if test is true. Because of the &&
short circuit operator, count is not incremented during the second if test.
Learn more problems on : Operators and Assignments
Discuss about this problem : Discuss in Forum
4.Which two statements are equivalent?
1. 3/2
2. 3<2
3. 3*4
4. 3<<2
A.1 and 2 B.2 and 3
C.3 and 4 D.1 and 4
Answer: Option C
Explanation:
(1) is wrong. 3/2 = 1 (integer arithmetic).
(2) is wrong. 3 < 2 = false.
(3) is correct. 3 * 4 = 12.
(4) is correct. 3 <<2= 12. In binary 3 is 11, now shift the bits two places to the left and we get
1100 which is 12 in binary (3*2*2).
17. Learn more problems on : Operators and Assignments
Discuss about this problem : Discuss in Forum
5.public void foo( boolean a, boolean b)
{
if( a )
{
System.out.println("A"); /* Line 5 */
}
else if(a && b) /* Line 7 */
{
System.out.println( "A && B");
}
else /* Line 11 */
{
if ( !b )
{
System.out.println( "notB") ;
}
else
{
System.out.println( "ELSE" ) ;
}
}
}
A.If a is true and b is true then the output is "A && B"
B.If a is true and b is false then the output is "notB"
C.If a is false and b is true then the output is "ELSE"
D.If a is false and b is false then the output is "ELSE"
Answer: Option C
Explanation:
Option C is correct. The output is "ELSE". Only when a is false do the output lines after 11 get
some chance of executing.
Option A is wrong. The output is "A". When a is true, irrespective of the value of b, only the
line 5 output will be executed. The condition at line 7 will never be evaluated (when a is true it
will always be trapped by the line 12 condition) therefore the output will never be "A && B".
Option B is wrong. The output is "A". When a is true, irrespective of the value of b, only the
line 5 output will be executed.
Option D is wrong. The output is "notB".
Learn more problems on : Flow Control
Discuss about this problem : Discuss in Forum
18. 6.What will be the output of the program?
Float f = new Float("12");
switch (f)
{
case 12: System.out.println("Twelve");
case 0: System.out.println("Zero");
default: System.out.println("Default");
}
A.Zero B.Twelve
C.Default D.Compilation fails
Answer: Option D
Explanation:
The switch statement can only be supported by integers or variables more "narrow" than an
integer i.e. byte, char, short. Here a Float wrapper object is used and so the compilation fails.
Learn more problems on : Flow Control
Discuss about this problem : Discuss in Forum
7.What will be the output of the program?
public class Test
{
public static void aMethod() throws Exception
{
try /* Line 5 */
{
throw new Exception(); /* Line 7 */
}
finally /* Line 9 */
{
System.out.print("finally "); /* Line 11 */
}
}
public static void main(String args[])
{
try
{
aMethod();
}
catch (Exception e) /* Line 20 */
{
System.out.print("exception ");
}
System.out.print("finished"); /* Line 24 */
}
}
A.finally
19. B.exception finished
C.finally exception finished
D.Compilation fails
Answer: Option C
Explanation:
This is what happens:
(1) The execution of the try block (line 5) completes abruptly because of the throw statement
(line 7).
(2) The exception cannot be assigned to the parameter of any catch clause of the try statement
therefore the finally block is executed (line 9) and "finally" is output (line 11).
(3) The finally block completes normally, and then the try statement completes abruptly
because of the throw statement (line 7).
(4) The exception is propagated up the call stack and is caught by the catch in the main method
(line 20). This prints "exception".
(5) Lastly program execution continues, because the exception has been caught, and "finished"
is output (line 24).
Learn more problems on : Exceptions
Discuss about this problem : Discuss in Forum
8.Which statement is true for the class java.util.ArrayList?
A.The elements in the collection are ordered.
B.The collection is guaranteed to be immutable.
C.The elements in the collection are guaranteed to be unique.
D.The elements in the collection are accessed using a unique key.
Answer: Option A
Explanation:
Yes, always the elements in the collection are ordered.
Learn more problems on : Objects and Collections
Discuss about this problem : Discuss in Forum
9.Which is true about a method-local inner class?
20. A.It must be marked final.
B.It can be marked abstract.
C.It can be marked public.
D.It can be marked static.
Answer: Option B
Explanation:
Option B is correct because a method-local inner class can be abstract, although it means a
subclass of the inner class must be created if the abstract class is to be used (so an abstract
method-local inner class is probably not useful).
Option A is incorrect because a method-local inner class does not have to be declared final
(although it is legal to do so).
C and D are incorrect because a method-local inner class cannot be made public (remember-
you cannot mark any local variables as public), or static.
Learn more problems on : Inner Classes
Discuss about this problem : Discuss in Forum
10.class X implements Runnable
{
public static void main(String args[])
{
/* Missing code? */
}
public void run() {}
}
Which of the following line of code is suitable to start a thread ?
A.Thread t = new Thread(X);
B.Thread t = new Thread(X); t.start();
C.X run = new X(); Thread t = new Thread(run); t.start();
D.Thread t = new Thread(); x.run();
Answer: Option C
Explanation:
Option C is suitable to start a thread.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
21. 11.What will be the output of the program?
class MyThread extends Thread
{
public static void main(String [] args)
{
MyThread t = new MyThread();
t.start();
System.out.print("one. ");
t.start();
System.out.print("two. ");
}
public void run()
{
System.out.print("Thread ");
}
}
A.Compilation fails
B.An exception occurs at runtime.
C.It prints "Thread one. Thread two."
D.The output cannot be determined.
Answer: Option B
Explanation:
When the start() method is attempted a second time on a single Thread object, the method
will throw an IllegalThreadStateException (you will not need to know this exception name
for the exam). Even if the thread has finished running, it is still illegal to call start() again.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
12.What will be the output of the program?
class MyThread extends Thread
{
MyThread() {}
MyThread(Runnable r) {super(r); }
public void run()
{
System.out.print("Inside Thread ");
}
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.print(" Inside Runnable");
}
}
22. class Test
{
public static void main(String[] args)
{
new MyThread().start();
new MyThread(new MyRunnable()).start();
}
}
A.Prints "Inside Thread Inside Thread"
B.Prints "Inside Thread Inside Runnable"
C.Does not compile
D.Throws exception at runtime
Answer: Option A
Explanation:
If a Runnable object is passed to the Thread constructor, then the run method of the Thread
class will invoke the run method of the Runnable object.
In this case, however, the run method in the Thread class is overridden by the run method in
MyThread class. Therefore the run() method in MyRunnable is never invoked.
Both times, the run() method in MyThread is invoked instead.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
13.What will be the output of the program?
class s implements Runnable
{
int x, y;
public void run()
{
for(int i = 0; i < 1000; i++)
synchronized(this)
{
x = 12;
y = 12;
}
System.out.print(x + " " + y + " ");
}
public static void main(String args[])
{
s run = new s();
Thread t1 = new Thread(run);
Thread t2 = new Thread(run);
t1.start();
t2.start();
23. }
}
A.DeadLock B.It print 12 12 12 12
C.Compilation Error D.Cannot determine output.
Answer: Option B
Explanation:
The program will execute without any problems and print 12 12 12 12.
Learn more problems on : Threads
Discuss about this problem : Discuss in Forum
14.public class Test
{
public void foo()
{
assert false; /* Line 5 */
assert false; /* Line 6 */
}
public void bar()
{
while(true)
{
assert false; /* Line 12 */
}
assert false; /* Line 14 */
}
}
What causes compilation to fail?
A.Line 5
B.Line 6
C.Line 12
D.Line 14
Answer: Option D
Explanation:
Option D is correct. Compilation fails because of an unreachable statement at line 14. It is a
compile-time error if a statement cannot be executed because it is unreachable. The question
is now, why is line 20 unreachable? If it is because of the assert then surely line 6 would also
be unreachable. The answer must be something other than assert.
Examine the following:
24. A while statement can complete normally if and only if at least one of the following is true:
- The while statement is reachable and the condition expression is not a constant expression
with value true.
-There is a reachable break statement that exits the while statement.
The while statement at line 11 is infinite and there is no break statement therefore line 14 is
unreachable. You can test this with the following code:
public class Test80
{
public void foo()
{
assert false;
assert false;
}
public void bar()
{
while(true)
{
assert false;
break;
}
assert false;
}
}
Learn more problems on : Assertions
Discuss about this problem : Discuss in Forum
15.What will be the output of the program?
public class Test
{
public static int y;
public static void foo(int x)
{
System.out.print("foo ");
y = x;
}
public static int bar(int z)
{
System.out.print("bar ");
return y = z;
}
public static void main(String [] args )
{
int t = 0;
assert t > 0 : bar(7);
assert t > 1 : foo(8); /* Line 18 */
System.out.println("done ");
}
25. }
A.bar
B.bar done
C.foo done
D.Compilation fails
Answer: Option D
Explanation:
The foo() method returns void. It is a perfectly acceptable method, but because it returns void
it cannot be used in an assert statement, so line 18 will not compile.
Learn more problems on : Assertions
Discuss about this problem : Discuss in Forum
16.Which of the following statements is true?
A.In an assert statement, the expression after the colon ( : ) can be any Java expression.
B.If a switch block has no default, adding an assert default is considered appropriate.
C.
In an assert statement, if the expression after the colon ( : ) does not have a value, the
assert's error message will be empty.
D.It is appropriate to handle assertion failures using a catch clause.
Answer: Option B
Explanation:
Adding an assertion statement to a switch statement that previously had no default case is
considered an excellent use of the assert mechanism.
Option A is incorrect because only Java expressions that return a value can be used. For
instance, a method that returns void is illegal.
Option C is incorrect because the expression after the colon must have a value.
Option D is incorrect because assertions throw errors and not exceptions, and assertion errors
do cause program termination and should not be handled.
Learn more problems on : Assertions
Discuss about this problem : Discuss in Forum
17.public class Test2
{
public static int x;
public static int foo(int y)
26. {
return y * 2;
}
public static void main(String [] args)
{
int z = 5;
assert z > 0; /* Line 11 */
assert z > 2: foo(z); /* Line 12 */
if ( z < 7 )
assert z > 4; /* Line 14 */
switch (z)
{
case 4: System.out.println("4 ");
case 5: System.out.println("5 ");
default: assert z < 10;
}
if ( z < 10 )
assert z > 4: z++; /* Line 22 */
System.out.println(z);
}
}
which line is an example of an inappropriate use of assertions?
A.Line 11
B.Line 12
C.Line 14
D.Line 22
Answer: Option D
Explanation:
Assert statements should not cause side effects. Line 22 changes the value of z if the assert
statement is false.
Option A is fine; a second expression in an assert statement is not required.
Option B is fine because it is perfectly acceptable to call a method with the second expression
of an assert statement.
Option C is fine because it is proper to call an assert statement conditionally.
Learn more problems on : Assertions
Discuss about this problem : Discuss in Forum
18.What will be the output of the program?
public class NFE
{
27. public static void main(String [] args)
{
String s = "42";
try
{
s = s.concat(".5"); /* Line 8 */
double d = Double.parseDouble(s);
s = Double.toString(d);
int x = (int) Math.ceil(Double.valueOf(s).doubleValue());
System.out.println(x);
}
catch (NumberFormatException e)
{
System.out.println("bad number");
}
}
}
A.42
B.42.5
C.43
D.bad number
Answer: Option C
Explanation:
All of this code is legal, and line 8 creates a new String with a value of "42.5". Lines 9 and 10
convert the String to a double and then back again. Line 11 is fun— Math.ceil()'s argument
expression is evaluated first. We invoke the valueOf() method that returns an anonymous
Double object (with a value of 42.5). Then the doubleValue() method is called (invoked on
the newly created Double object), and returns a double primitive (there and back again), with
a value of (you guessed it) 42.5. The ceil() method converts this to 43.0, which is cast to an
int and assigned to x.
Learn more problems on : Java.lang Class
Discuss about this problem : Discuss in Forum
19.What will be the output of the program?
public class Test138
{
public static void stringReplace (String text)
{
text = text.replace ('j' , 'c'); /* Line 5 */
}
public static void bufferReplace (StringBuffer text)
{
text = text.append ("c"); /* Line 9 */
}
public static void main (String args[])
28. {
String textString = new String ("java");
StringBuffer textBuffer = new StringBuffer ("java"); /* Line 14 */
stringReplace(textString);
bufferReplace(textBuffer);
System.out.println (textString + textBuffer);
}
}
A.java
B.javac
C.javajavac
D.Compile error
Answer: Option C
Explanation:
A string is immutable, it cannot be changed, that's the reason for the StringBuffer class. The
stringReplace method does not change the string declared on line 14, so this remains set to
"java".
Method parameters are always passed by value - a copy is passed into the method - if the
copy changes, the original remains intact, line 5 changes the reference i.e. text points to a new
String object, however this is lost when the method completes. The textBuffer is a
StringBuffer so it can be changed.
This change is carried out on line 9, so "java" becomes "javac", the text reference on line 9
remains unchanged. This gives us the output of "javajavac"
Learn more problems on : Java.lang Class
Discuss about this problem : Discuss in Forum
20.What will be the output of the program (in jdk1.6 or above)?
public class BoolTest
{
public static void main(String [] args)
{
Boolean b1 = new Boolean("false");
boolean b2;
b2 = b1.booleanValue();
if (!b2)
{
b2 = true;
System.out.print("x ");
}
if (b1 & b2) /* Line 13 */
{
System.out.print("y ");