Java Section 5: Methods and Variables
23 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

Which primitive data types can be implicitly promoted to a double?

  • `float`, `int`, `char`
  • `long`, `int`, `short`, `byte`
  • Only `float`
  • `float`, `long`, `int`, `char`, `short`, `byte` (correct)
  • What is the result of the following expression: (int) (4.8 + 2.3)?

  • 6.0
  • 6
  • 7.1
  • 7 (correct)
  • Which of the following statements regarding type casting is correct?

  • Casting of a `long` type to an `int` is guaranteed not to cause any errors.
  • Implicit casting of a floating-point number will round the fractional part to the nearest integer.
  • Implicit type casting from `double` to `int` will cause a compilation error. (correct)
  • Explicit casting is allowed when going from lower to higher data types in the table
  • If a method requires a double parameter but an int is passed, what happens?

    <p>The <code>int</code> is implicitly promoted to a <code>double</code> before the method call. (C)</p> Signup and view all the answers

    Which type promotions occur in the expression: 1.5 * 4, if the result is stored as a double?

    <p>The integer 4 is promoted to a double 4.0. (D)</p> Signup and view all the answers

    How many instances of a static variable are created in a Java class?

    <p>One per class, shared by all objects of that class. (A)</p> Signup and view all the answers

    Which of the following primitive types can be explicitly cast to a short?

    <p><code>byte</code>, <code>int</code>, <code>long</code>, <code>float</code>, <code>double</code> (D)</p> Signup and view all the answers

    What is the correct syntax to call a static method calculateSum() within the same class?

    <p><code>calculateSum(arguments);</code> (B)</p> Signup and view all the answers

    What happens during the execution of the code: int x =(int) 5.9;?

    <p>The variable x will have the value 5 (C)</p> Signup and view all the answers

    Which statement best describes a static method in Java?

    <p>It can only access static variables of the class. (D)</p> Signup and view all the answers

    What is the key characteristic of method overloading in Java?

    <p>Methods must have different parameter lists. (B)</p> Signup and view all the answers

    If a static method processData() is defined in a class named DataHandler, how would you call it from a different class?

    <p><code>DataHandler.processData(arguments);</code> (D)</p> Signup and view all the answers

    Which access modifier is always used for the main method in Java?

    <p><code>public</code> (C)</p> Signup and view all the answers

    What determines which overloaded method will be called?

    <p>The number of parameters and their types, return type is ignored. (A)</p> Signup and view all the answers

    Why is the main method declared as static in Java?

    <p>To ensure that it can be called by the JVM without creating an instance of the class. (B)</p> Signup and view all the answers

    What happens in Java when a method parameter is declared as a double and is passed an int value?

    <p>The <code>int</code> value is promoted (converted) to a <code>double</code> before being passed. (B)</p> Signup and view all the answers

    How are command line arguments passed to a Java application?

    <p>As elements of the <code>args</code> array in the <code>main</code> method. (A)</p> Signup and view all the answers

    Which of the following is an example of method overloading?

    <p><code>public void myMethod(int a)</code> and <code>public void myMethod(int a, int b)</code> (C)</p> Signup and view all the answers

    What is the key difference between instance variables and static variables?

    <p>Each object gets its own copy of instance variables, while all objects share one copy of static variables. (C)</p> Signup and view all the answers

    If a method is trying to access a variable and that variable is not defined in the method's scope, or as an instance variable, or a static variable, a compiler error will usually occur, but if the variable is of a lower type than the method's parameter, argument promotion will make the code:

    <p>Work correctly as the type will be promoted if needed. (B)</p> Signup and view all the answers

    Which of the following is correct, regarding return statements in methods that return a value?

    <p>Methods that return a value must have a return statement that matches the defined method return type. (C)</p> Signup and view all the answers

    If a class University has several modules from different faculties, which type of variable would be most suitable for storing the university name?

    <p>A static variable shared by all module objects. (B)</p> Signup and view all the answers

    What is the commonly known name for static variables?

    <p>Class Variables (C)</p> Signup and view all the answers

    Study Notes

    Java Section 5: More on Methods and Variables

    • Methods and variables will be explored in more detail.
    • Examples will be reviewed to reinforce learning.

    Java Section 5: More about Methods

    • Java Programs and Classes
    • Static methods
    • Static variables
    • Method calls
    • Method overloading
    • Variable-length argument lists
    • Command-line arguments
    • JOptionDialog
    • Wrapper Classes
    • Case studies
    • Lectures will emphasize important concepts.
    • Students should also read the recommended readings and complete the associated exercises.

    BlueJ: Java5_Examples[MoreMethods Variables]

    • Examples related to methods and variables are available in a BlueJ project.
    • Click on the README.TXT file to get a brief description of available classes.
    • Classes that are related are grouped together for easy access and comparison, though they may normally be in more than one project.

    Various Method Examples

    • FindMax4: Demonstrates a static method and calling it using the class name.
    • SequenceStatic: Displays a sequence to illustrate static methods and a static variable.
    • ExploreStatic: Explores static variables and methods.
    • SumOverload: Demonstrates method overloading and type conversion.
    • VariableLengthArgs: Demonstrates variable length argument lists using a min method.
    • CommandLineArgs: Demonstrates command-line argument lists.
    • RandomFairDice, BarChart, CalculatePi, Card, CardDeck, TestCardDeck: Application case studies demonstrating concepts covered in the course.

    Java Programs and Classes

    • OO systems use classes as building blocks
    • Java programs are made up of classes that contain fields (variables) and methods (actions).
    • Fields store features or properties, while methods define behaviors.
    • Implementing a solution often requires leveraging existing (and new) components.
    • OO Systems are made through iterations: Specification, Design, Code, and Test.
    • Reusability of existing well-tested components is encouraged.

    Instance Variables and Instance Methods

    • Instance variables store object attributes. (e.g., private String name; private int quantity;)
    • Each object has its own set of instance variables.
    • Instance methods access/modify instance variables.
    • Get methods retrieve data (e.g., getName()).
    • Set methods modify data (e.g., setName()).
    • Instance methods are called through an object of its class (objectReference.methodName(arguments)).

    Static Methods

    • Static methods don't depend on instance variables.
    • Static methods are called directly using the class name (ClassName.methodName(arguments)). or through a class reference(methodName(arguments)) if within the same class.
    • Static methods are beneficial for tasks applicable to all instances.
    • Java class Math, Arrays and other classes include static methods for mathematical and array handling.
    • Static methods are declared using the keyword static before the return type. (e.g., public static double max(double a, double b, double c, double d))

    The Main Method

    • The main method in a Java program is static.
    • The Java Virtual Machine (JVM) locates the main method to execute an application.
    • The main method is invoked when the program runs.
    • The main method's parameter String[] args represents command-line arguments.

    Static Variables (aka Class Variables)

    • Static variables belong to the class, not instances.
    • Every object of a class shares a single copy of the static variable.
    • private static int countToSeqStringCalls = 0; (example of static variable).
    • Static variables and instance variables make up the fields of a class.

    Static Methods and Variables (ExploreStatic)

    • ExploreStatic class provides static methods from the MyMath challenge. (e.g., factorial, biCoeff, power )
    • ExploreStatic demonstrates method calls and static variable use.

    Java Class Math

    • The Math class in java.lang contains static methods for mathematical operations.
    • Methods like abs, cos, exp, log, min, max(a,b), or pow are available.
    • Constants such as Math.PI and Math.E are available.
    • These will be declared and used with static modifier keywords.

    Methods (Declaration, Formal Parameters & Actual Arguments)

    • Each method is part of a class.
    • Parameters and their types are explicitly defined in the method declaration.
    • Multiple parameters are listed separated by commas.
    • When calling a method, the method requires an argument value corresponding to every formal parameter.

    Calling Methods

    • Methods can be called through their name,
    • through an existing object,
    • or through the class name (static methods).

    Returning from a Method

    • Methods can return a result.
    • The return statement is used to return values from a method.
    • A method's return value type is specified in its declaration as part of its formal parameters.
    • Return types such as int, double and void are possible.

    Static vs. Instance Fields and Methods

    • Static variables are shared among all objects of a class; instance variables are unique to each object.
    • Static methods can be called directly without creating an object; instance methods require an object reference.

    Method Overloading

    • Methods can have the same name if their parameter lists are different.
    • The compiler selects the appropriate method based on the number and types of arguments.
    • Return types are not considered.

    Argument Promotion

    • Primitive data types are promoted to higher types if the method expects a higher data type.
    • Parameter types of double, float, long, int, char, short, byte, boolean is used to decide the method type.

    Casting

    • Explicit conversion between data types is called casting.
    • It can result in a loss of precision.
    • When converting floating-point numbers to integers, the fractional part will be truncated.

    Passing Arguments to Methods

    • Arguments passed to methods are promoted to compatible types (if needed).
    • The MyMath class that has an average() method demonstrates argument promotion for calculations.

    Scope of Declarations

    • Scope refers to a part of a class or method that can access a variable or method.
    • Local variables are only valid within a block of code.
    • Parameters are in scope during the entire method.
    • Method and field scope extends throughout the entire class body.

    Variable-Length Argument Lists

    • Variable-length argument lists allow methods to accept a varying number of arguments of specific types.
    • int min(int... numbers) declares a method accepting any number of integers.

    Command-Line Arguments

    • Arguments passed to a Java program via command line are treated as an array of strings.
    • The arguments are accessible through the args array, which is passed into the program's main() method.

    Graphical User Interface (GUI) using JOptionPane

    • GUIs enhance user interaction by using windows/dialogs.
    • JOptionPane is a Java GUI component.
    • JOptionPane facilitates user input/output via dialog boxes and showInputDialog for input, showMessageDialog for output, among other methods to interact with users.
    • Input received from JOptionPane is typically a string, and needs to be converted to desired primitive data types using methods like Integer.parseInt.

    Java Primitive Wrapper Classes

    • Wrapper classes are object counterparts of primitive data types (int,double,float,boolean,char,byte,short,long).
    • These are in java.lang package so they don't need to be imported.
    • Methods are included in the wrappers.

    JOptionPane Exercises

    • Example of using JOptionPane for input and output.
    • Example of using a Dialog.java class to find the volume of a cone, including user input via showInputDialog and the output of the calculation using showMessageDialog.
    • Practice with different JOptionPane methods ( such as showMessageDialog).
    • Explore other methods and their usage from the API documentation.

    Application Case Studies

    • Students can explore source code for classes like RandomFairDice, BarChart, CalculatePi, and CardDeck.
    • Creating a copy of these classes to experiment and modify them can be helpful

    Deck of Cards

    • Class CardDeck handles standard decks of cards, adding features such as shuffling, dealing, peeking.
    • The basic operation of shuffling using a random select/swap algorithm.

    Static and Instance Methods and Variables Exercise

    • Exercise focuses on using static/instance methods and variables through the creation of a Class named Student.

    Next Semester

    • The syllabus for the next semester is presented.

    Studying That Suits You

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

    Quiz Team

    Related Documents

    Description

    This quiz delves into Java's methods and variables, providing a comprehensive overview of concepts such as static methods, method overloading, and variable-length argument lists. Through examples and case studies, students will reinforce their understanding of these fundamental programming topics. Be prepared to explore the relevant Java classes and complete associated exercises.

    More Like This

    Java Methods and Object Relationships
    12 questions
    JAVA Chapter 8 Flashcards
    14 questions
    Static Variables and Methods in Java
    8 questions
    Java Static Concepts
    8 questions

    Java Static Concepts

    TopInspiration7420 avatar
    TopInspiration7420
    Use Quizgecko on...
    Browser
    Browser