Java/code

Advertisement


Question
What does the following Java code fragment write to the monitor?

int sum = 25;
if ( sum < 20 )
       System.out.print("CSEN102 is ");
       System.out.println("great.");

Answer
It prints "great". If statements that aren't followed with a { } block will only include code as part of the if block until ; is reached.

E.g.

int sum = 25;
if ( sum < 20 );
      System.out.print("CSEN102 is ");
      System.out.println("great.");


will print "CSEN102 is great" since there is a ';' after the if statement. While


int sum = 25;
if ( sum < 20 )
{
      System.out.print("CSEN102 is ");
      System.out.println("great.");
}


will print nothing as both statements are in the if block.


int sum = 25;
if ( sum < 20 );
{
      System.out.print("CSEN102 is ");
      System.out.println("great.");
}


will print "CSEN102 is great." since there is a semicolon after the if statement, meaning it does nothing, and the following block is executed always.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.