Win a copy of Zero to AI - A non-technical, hype-free guide to prospering in the AI era this week in the Artificial Intelligence and Machine Learning forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Paul Clapham
  • Bear Bibeault
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Jj Roberts
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • salvin francis
  • Scott Selikoff
  • fred rosenberger

mock exam question on == and equals method

 
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Please see the mock question below
public class AssertionTest{
String s1;
String s2 = "hello";
String s3;
AssertionTest() {
s1 = "hello";
}

public static void main(String[] args) {
(new AssertionTest()).f();
}

{
s3 = "hello";
}

void f() {
String s4 = "hello";
String s5 = new String("hello");
assert(s1.equals(s2)); // (1)
assert(s2.equals(s3)); // (2)
assert(s3 == s4); // (3)
assert(s4 == s5); // (4)
}
}

Select the one correct answer.

The compilation will fail.

a) The assertion on the line marked (1) will fail.

b) The assertion on the line marked (2) will fail.

c) The assertion on the line marked (3) will fail.

d) The assertion on the line marked (4) will fail.

e) The program will run without any errors.

the answer is e)
but I thought s4 and s5 referring to different object since s5 is pointing to the new object String("hello")

could anyone give me the explanation.

Thank you and Regards,

Sura
 
Ranch Hand
Posts: 298
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After looking at this example, I feel that I know nothing about assertions.

Please someone write one single line about the use of assertions.

In this example, even if a value is returning false, the whole programming is compiling and running fine.

Please someone explain this.

Actually, s4==s5 is returning 'false' but there is no action taking place.

Kaps
 
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
guys,
The correct answer is d.
 
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Please someone explain this.

Actually, s4==s5 is returning 'false' but there is no action taking place.


Asertions are disabled by default.

Try it again with:
java -ea AssertionTest
 
Something must be done about this. Let's start by reading this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic