Java Methods and Parameters
39 Questions
0 Views

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

What does the printf method allow you to do?

  • Write formatted strings to the output stream. (correct)
  • Modify the appearance of numeric data only.
  • Store formatted strings in a variable.
  • Format strings into variables.
  • Which of the following methods returns a formatted string instead of printing it directly?

  • printf
  • System.out.println
  • String.format (correct)
  • DecimalFormat
  • Which symbol is used to start a format specifier in the printf method?

  • #
  • % (correct)
  • &
  • @
  • What is the purpose of the DecimalFormat class in Java?

    <p>To format numbers based on custom patterns.</p> Signup and view all the answers

    How do you specify the number of decimal places for a floating-point number in the printf method?

    <p>Using a precision specifier like <code>%.2f</code>.</p> Signup and view all the answers

    Which of the following is NOT a method for output formatting in Java?

    <p>InputStream</p> Signup and view all the answers

    When using String.format, what is the output of the following code: String formatted = String.format("Price: $%.2f", 19.99); System.out.println(formatted);?

    <p>Price: $19.99</p> Signup and view all the answers

    What is the primary purpose of the Scanner class in Java?

    <p>To read user input.</p> Signup and view all the answers

    What will be the output of System.out.printf("Hello %s! You are %d years old.", "Alice", 25);?

    <p>Hello Alice! You are 25 years old.</p> Signup and view all the answers

    Which method would you use to read an integer value from the keyboard using Scanner?

    <p>nextInt()</p> Signup and view all the answers

    Which of the following statements is true about closing a Scanner object?

    <p>It releases the associated input stream.</p> Signup and view all the answers

    What is the conversion formula for Celsius to Fahrenheit?

    <p>Fahrenheit = (Celsius * 9/5) + 32</p> Signup and view all the answers

    What is the first step in reading input from the keyboard using Scanner?

    <p>Import the Scanner class.</p> Signup and view all the answers

    What will the method nextDouble() return when called?

    <p>A double value.</p> Signup and view all the answers

    In a program calculating the sum and average of three integers, what should be the last step after calculations?

    <p>Print out the sum and the average.</p> Signup and view all the answers

    What will happen if the Scanner instance is not closed after its use?

    <p>It may lead to resource leaks.</p> Signup and view all the answers

    What will be the output of the following code if time is set to 22?

    if (time < 10) {
        System.out.println("Good morning.");
    } else if (time < 18) {
        System.out.println("Good day.");
    } else {
        System.out.println("Good evening.");
    }
    

    <p>Good evening.</p> Signup and view all the answers

    What operator checks if two operands are not equal?

    <p>!=</p> Signup and view all the answers

    What will the modulus operator (%) return when applied as in 5 % 2?

    <p>1</p> Signup and view all the answers

    Which of the following syntax is correct for a switch statement?

    <p>switch(expression) { case x: // code }</p> Signup and view all the answers

    Identify the main purpose of using a switch statement over if-else statements.

    <p>It simplifies the management of multiple conditional branches.</p> Signup and view all the answers

    In shorthand if-else syntax, what does the following code output?

    int time = 20;
    String result = (time < 18) ? "Good day." : "Good evening.";
    System.out.println(result);
    

    <p>Good evening.</p> Signup and view all the answers

    What is the outcome when using the equal to (==) operator between two operands with different data types?

    <p>It may return true, depending on the type conversion.</p> Signup and view all the answers

    What does the following if-else structure imply?

    if (condition) {
        // block of code if true
    } else {
        // block of code if false
    }
    

    <p>Only one block of code executes based on the condition's truth value.</p> Signup and view all the answers

    Which of the following is a valid method declaration in Java?

    <p>public void methodName(){}</p> Signup and view all the answers

    What does the return type of a method specify?

    <p>The type of value the method returns</p> Signup and view all the answers

    What happens when a method has a return type of void?

    <p>It does not return any value.</p> Signup and view all the answers

    How does System.out.println differ from System.out.print?

    <p>It appends a newline character after printing.</p> Signup and view all the answers

    What is the correct way to call a method named 'add' that takes two integer arguments?

    <p>add(5, 7)</p> Signup and view all the answers

    What will the output be when the following code is executed?

    System.out.println("Hello" + 5); 
    

    <p>Hello5</p> Signup and view all the answers

    What is the primary purpose of using parameters in methods?

    <p>To allow methods to operate on different data</p> Signup and view all the answers

    In the AverageCalculator program, how is the average calculated given two integer values?

    <p>average = (firstNumber + secondNumber) / 2.0;</p> Signup and view all the answers

    Which of the following correctly describes the parameters in the method declaration?

    public int add(int a, int b) { return a + b; } 
    

    <p>They specify the data the method will receive.</p> Signup and view all the answers

    What is the output when the user inputs the name 'Alice' and age '25' in the InputExample program?

    <p>Hello, Alice! You are 25 years old.</p> Signup and view all the answers

    Which of the following best defines a unary operator?

    <p>An operator that requires only one operand.</p> Signup and view all the answers

    Which arithmetic operation does not use binary operators?

    <p>Increment</p> Signup and view all the answers

    What does the increment operator in Java do when placed before a variable (e.g., ++x)?

    <p>Increases the variable's value before the expression is evaluated.</p> Signup and view all the answers

    What will happen if the user inputs a non-integer value when prompted for an integer in the AverageCalculator program?

    <p>An exception is thrown and the program crashes.</p> Signup and view all the answers

    In the statement 'int age = scanner.nextInt();', what data type is the variable age?

    <p>Integer</p> Signup and view all the answers

    Study Notes

    Methods in Java

    • Parameters allow methods to operate on different data without changing the method's code.
    • The return type specifies the type of value returned by a method; common return types include int, void, etc.
    • Method Definition Example:
      • public int add(int a, int b) defines a method add that returns an integer value.
      • The body of the method is enclosed in {}, executing operations like return a + b;.
    • Method Calling Example:
      • public void demoAdd() showcases calling the add method and printing the result.

    Output Formatting in Java

    • System.out.println outputs data to the console and appends a newline character.
    • To avoid a newline, utilize System.out.print.
    • Common use cases for output include debugging, logging, and user interfaces.
    • The method accepts any data type as an expression, providing its string representation.

    Formatting Techniques

    • printf Method:
      • Writes formatted strings to the output using format specifiers that begin with %, e.g., System.out.printf("Name: %s, Age: %d\n", "John Doe", 30);.
    • String.format Method:
      • Similar to printf, but returns a formatted string instead of printing it immediately.
      • Example: String formattedString = String.format("Height: %.1f cm", 172.3);.
    • DecimalFormat Class:
      • Offers advanced number formatting capabilities, including custom patterns for decimal places and grouping.
      • Example: DecimalFormat decimalFormat = new DecimalFormat("#,###.00");.

    Input Handling in Java

    • The Scanner class from java.util reads user input, available for different data types.
    • Process for reading input includes:
      • Importing the Scanner class.
      • Creating an instance with Scanner scanner = new Scanner(System.in);.
      • Reading inputs using methods like nextInt() or nextLine().
      • Closing the scanner post-usage for resource management.
    • Example code reads user name and age, then prints a greeting.

    Operators in Java

    • Unary Operators: Operate on a single operand; for instance, increment (++), decrement (--), and logical NOT (!).
    • Binary Operators: Require two operands for operations such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and equality checks (==, !=).

    Decision Making and Branching

    • If...else Statements: Control flow based on boolean conditions.
      • Standard syntax distinguishes blocks of code executed based on the condition being true or false.
      • Example illustrates basic time-based greeting outputs.
    • Shorthand If...else: The ternary operator provides a compact syntax to assign values based on conditions, e.g., result = (time < 18) ? "Good day." : "Good evening.";.

    Switch Statements

    • Used as an alternative to multiple if...else statements for clearer selection of code blocks based on expression value.
    • Syntax includes defining cases and a default action:
      switch(expression) {
          case x:
              // code block
              break;
          default:
              // default code block
      }
      
    • Example illustrates a switch case that determines a day of the week from a numeric value.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Related Documents

    L_02_Java Fundamentals.pdf

    Description

    Explore the fundamentals of Java methods and parameters in this quiz. Learn how to define methods, understand return types, and practice with examples like the 'add' method. Test your knowledge on methods that allow flexibility in coding without changing the underlying code.

    More Like This

    Java Methods and Object Relationships
    12 questions
    مقدمة إلى الطرق في جافا
    25 questions
    Java Basics: Constructors and Identifiers
    21 questions
    Use Quizgecko on...
    Browser
    Browser