COP3022 Midterm 1 Study Guide

¡Supera tus tareas y exámenes ahora con Quizwiz!

Inheritance: Super and Sub Class

(Base and Derived Class) Definitions: Base class: AKA Super Derived class: AKA Sub: refers to a class that is derived from the Superclass. Relationship: The derived (sub) class is said to inherit the properties of its base class, a concept commonly called inheritance. How instance are handled: An object declared of a derived class type has access to all the public members of the derived class as well as the public members of the base class. class SubclassName extends SuperclassName { }

Identifier Rules

-The first character of an identifier must be an alphabetic character or and underscore ( _ ), -After the first character you may use alphabetic characters, numbers, or underscore characters. -Upper- and lowercase characters are distinct Definition: An Identifier is a name created by a programmer for an item like a variable or method. They are case sensitive. A reserved word (AKA keyword) is a word that is part of the language, like int, short, or double. Lower camel case abuts multiple words, capitalizing each word except the first, as in numApples or peopleOnBus.

Code Comp: Selection - compareTo()

/** This program compares two String objects using the compareTo method. */ public class StringCompareTo { public static void main(String [] args) { String name1 = "Mary", name2 = "Mark"; // Compare "Mary" and "Mark" if (name1.compareTo(name2) < 0) { System.out.println(name1 + " is less than " + name2); } else if (name1.compareTo(name2) == 0) { System.out.println(name1 + " is equal to " + name2); } else if (name1.compareTo(name2) > 0) { System.out.println(name1 + " is greater than " + name2); } } }

Arrays

1) Declaring, creating, and initializing arrays: dataType[] arrayName = new dataType[numElements]; public class ArrayExample { public static void main (String [] args) { int[] itemCounts = new int[3]; itemCounts[0] = 122; itemCounts[1] = 119; itemCounts[2] = 117; System.out.print(itemCounts[1]); } } If the array size is unknown during declaration: int[] gameScores; . . . gameScores = new int[4]; Another type of declaration: int[] myArray = {5, 7, 11}; SO, myArray[1] = 7 2) Accessing arrays: import java.util.Scanner; public class OldestPeople { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int[] oldestPeople = new int[5]; int nthPerson; // User input, Nth oldest person oldestPeople[0] = 122; // Died 1997 in France oldestPeople[1] = 119; // Died 1999 in U.S. oldestPeople[2] = 117; // Died 1993 in U.S. oldestPeople[3] = 117; // Died 1998 in Canada oldestPeople[4] = 116; // Died 2006 in Ecuador System.out.print("Enter N (1-5): "); nthPerson = scnr.nextInt(); if ((nthPerson >= 1) && (nthPerson <= 5)) { System.out.print("The " + nthPerson + "th oldest person lived "); System.out.println(oldestPeople[nthPerson - 1] + " years."); } } } OUTPUT: Enter N (1-5): 1 The 1th oldest person lived 122 years. 3) Arrays of primitive types A variable of primitive type(like int or char) is passed to a method by passing the value of the variable, meaning the argument's value is copied into a local variable for the parameter. As such, any assignments to parameters do not affect the arguments, because the parameter is a copy. 4) Arrays of objects 5) Length of an array. String[] teamRoster = new String[3]; // Setting player names teamRoster[0] = "Mike"; teamRoster[1] = "Scottie"; teamRoster[2] = "Toni"; System.out.println("Current roster:"); for (int i = 0; i < teamRoster.length; ++i) { String playerName = teamRoster[i]; System.out.println(playerName); } 6)ArrayIndexOutOfBoundsException 7) For Each loops: a loop that iterates through each element in an array String[] teamRoster = new String[3]; // Setting player names teamRoster[0] = "Mike"; teamRoster[1] = "Scottie"; teamRoster[2] = "Toni"; System.out.println("Current roster:"); for (String playerName : teamRoster) { System.out.println(playerName); } 8) Partially filled arrays 9) Pass an array as a parameter import java.util.Scanner; public class ArrayReversal { public static void reverseVals(int[] arrVals, int arrSize) { int i; // Loop index int tmpStore; // Temp variable for swapping for (i = 0; i < (arrSize / 2); ++i) { tmpStore = arrVals[i]; // Do swap arrVals[i] = arrVals[arrSize - 1 - i]; arrVals[arrSize - 1 - i] = tmpStore; } } public static void main(String[] args) { Scanner scnr = new Scanner(System.in); final int NUM_VALUES = 8; // Array size int[] userVals = new int[NUM_VALUES]; // User values int i; // Loop index // Prompt user to populate array System.out.println("Enter " + NUM_VALUES + " values..."); for (i = 0; i < NUM_VALUES; ++i) { System.out.print("Value: "); userVals[i] = scnr.nextInt(); } // Call method to reverse array values reverseVals(userVals, NUM_VALUES); // Print updated arrays System.out.print("\nNew values: "); for (i = 0; i < NUM_VALUES; ++i) { System.out.print(userVals[i] + " "); } System.out.println(); } }

Flow of Control: "Boolean" Expression

A Boolean is a type that has just two values: True or False. Relational Operators 1) < : left-side less than right-side 2) >: left-side greater than right-side 3) <=: left-side less than or equal to right-side 4) >=: left-side greater than or equal to right-side 5) ==: left-side is equal to right-side 6) !=: left-side is NOT equal to right-side Strings: 1) equals(): The equals method returns true if the two strings are equal. if(userWord.equals("Voldemort")) { System.out.println("He who must not be named"); } 2) equalsIgnoreCase() str1.equalsIgnoreCase(str2); Allows programmers to compare strings while ignoring case; used in conjunction with compareToIgnoreCase(). 3) Lexicographical Ordering 4) compareTo() Compares strings relationally using the notation str1.compareTo(str2) < 0; // returns negative number str1.compareTo(str2) == 0; //returns 0 str1.compareTo(str2) > 0; //returns a positive number 5) compareToIgnoreCase() str1.compareToIgnoreCase(str2); Boolean Operators/Logical Operator 1) &&: true when both of its operands are true 2) ||: true when at least one of its two operands are true 3) Evaluation: 4) Lazy or Short Circuit: Boolean Variables: Loops: 1) while: Repeatedly executes a list of sub-statements (known as loop body) while the loop's expression evaluates to true. while (expression) { // Loop expression // Loop body: Executes if expression evaluated to true // After body, execution jumps back to the "while" } // Statements that execute after the expression evaluates to false 2) do while: Loop construct that first executes the loop body's statements, then checks the loop condition. do { // Loop body } while (loopExpression); 3) for for (initialExpression; conditionExpression; updateExpression) { // Loop body } // Statements after the loop Standard For Loop: int i; ... for (i = 0; i < N; ++i) { ... } 4)**pitfalls: Extra semicolon for loop; infinite loops: Loop that never stop iterating. off by one

Classes: Methods

A method is a named list of statements. public class PizzaArea { public static void printPizzaArea() { double pizzaDiameter; double pizzaRadius; double pizzaArea; double piVal = 3.14159265; pizzaDiameter = 12.0; pizzaRadius = pizzaDiameter / 2.0; pizzaArea = piVal * pizzaRadius * pizzaRadius; System.out.print(pizzaDiameter + " inch pizza is "); System.out.println(pizzaArea + " inches squared."); } public static void main (String [] args) { printPizzaArea(); } } 1) Accessors: An accessor method accesses fields but may not modify a class' fields. 2) Mutators: A mutator method may modify("mutate") a class' fields. 3) Passing Parameters: the type of data a method can receive is referred to as a parameter. The argument is 'what' is passed to a method. 4) Return type 5) Overloading 6) Methods that return a Boolean(predicate methods) MUTATOR AND ACCESSOR METHODS: Restaurant.java public class Restaurant { private String name; private int rating; public void setName(String restaurantName) { // Mutator name = restaurantName; } public void setRating(int userRating) { // Mutator rating = userRating; } public String getName() { // Accessor return name; } public int getRating() { // Accessor return rating; } public void print() { // Accessor System.out.println(name + " -- " + rating); } } MyRestaurant.java public class MyRestaurant { public static void main(String[] args) { Restaurant myPlace = new Restaurant(); myPlace.setName("Maria's Diner"); myPlace.setRating(5); System.out.print(myPlace.getName() + " is rated "); System.out.println(myPlace.getRating()); } } OUTPUT: Maria's Diner is rated 5

Input/Output: Packages

A package is a group of related classes. Ex: java.til.package - the Scanner class is located within the java.util.package. To use a class, a program must include an import statement that informs the compiler of the class' location. Import Statement: import packageName.ClassName; so, import java.util.Scanner;

Inheritance: "is a" v "has a"

A pear 'is a' kind of fruit. A house 'has a' door. The concept of inheritance is commonly confused with the idea of composition. Composition is the idea that one object may be made up of other objects, such as a MotherInfo class being made up of objects like firstName (which may be a String object), childrenData (which may be an ArrayList of ChildInfo objects), etc. Defining that MotherInfo class does not involve inheritance, but rather just composing the sub-objects in the class.

Flow of Control: "switch" Statements

A switch statement can more clearly represent multi-branch behavior involving a variable being compared to constant values. Code Example: numItems and userVal are int types. What is the final value of numItems for each userVal? switch (userVal) { case 1: numItems = 5; break; case 3: numItems = 12; break; case 4: numItems = 99; break; default: numItems = 55; break; } userVal = 3; Output: 12 The case with expression 3 will execute numItems = 12 and then break. userVal = 0; Output: 55 No case expression is 0, so the default case executes numItems = 55. userVal = 2; Output: 55 No case expression is 2, so the default case executes numItems = 55. The fact that 2 is between 1 and 3 is irrelevant.

Classes: Class Definition statement

A template that describes the data and behavior associated with instances of that class. class name { } The keyword class begins the class definition for a class called name.

Arithmetic Operations

Addition: (+) as in x + y; Subtraction : (-) as in x - y; Negation: (-x) Multiplication: (*) as in x * y; Division: (/) as in x/y; You must account for PEMDAS by using parentheses. (x * y) + z;

Assignment Statements

An assignment statement assigns the variable on the left-side of the = with the current value of the right-side expression.

Variable Assignments and Initialization:

An assignment statement uses the = operator to store a value in a variable. item = 12; This statement assigns the value 12 to the item variable. You can increment a variables value by 1, as in x = x + 1; This is common, and known as incrementing the variable.

Exception Handling

An exception is a circumstance that a program was not designed to handle. Exception-Handling Constructs: Try, throw, and catch; keeps error checking code separate to reduce redundant checks. Try/Catch Mechanism: Try: A try block surrounds normal code, which is exited immediately if a throw statement executes. Catch: A catch clause immediately follows a try block; if the catch was reached due to an exception thrown of the catch clause's parameter type, the clause executes. Catch Block and Catch Block parameter Exception Control Loops Throw Statement: appears within a try block; if reached, execution jumps immediately to the end of the try block. User Defined Exception (Defining an Exception Class) Multiple Exception Blocks Throwing Exception in a method Checked and UnChecked Exception: Checked exception: an exception that a programmer should be able to anticipate and appropriately handle. UnChecked Exception: exceptions that result from hardware or logic errors that typically cannot be anticipated or handled appropriately, and instead should be eliminated from the program or at the very least should cause the program to terminate immediately. Finally block: follows all catch blocks, and executes after the program exits the corresponding try or catch blocks. Rethrowing an Exception Code comprehension: Try/Catch/Finally Flow of Control Throwing Exceptions

Constants

An initialized variable whose value cannot change. AKA Final Variable

Integer Division

An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of times that the numerator is divisible by the denominator and discards any remainder.

Compilation Process

Compilation and execution of a Java program is two step process. During compilation phase Java compiler compiles the source code and generates bytecode. This intermediate bytecode is saved in form of a .class file. In second phase, Java virtual machine (JVM) also called Java interpreter takes the .class as input and generates output by executing the bytecode. Java is an object oriented programming language; therefore, a program in Java is made of one or more classes.

Classes: Constructors

Constructor: a Special class member method that is called when an object of that class type is created, and which can be used to initialize all fields. A default constructor is a constructor that can be called without any arguments. What makes them identifiable? A constructor has the same name as the class. It has no return type, not even void. Ex: public Restaurant() {...} What do they do? Initialize a newly created object and is called just after the memory is allocated for the object. Overloading: A class creator can overload a constructor by defining multiple constructors differing in parameter types. Constructor Code Example: Restaurant.java public class Restaurant { private String name; private int rating; public Restaurant() { // Default constructor name = "NoName"; // Default name: NoName indicates name was not set rating = -1; // Default rating: -1 indicates rating was not set } public void setName(String restaurantName) { name = restaurantName; } public void setRating(int userRating) { rating = userRating; } public void print() { System.out.println(name + " -- " + rating); } } RestaurantFavorites.java public class RestaurantFavorites { public static void main(String[] args) { Restaurant favLunchPlace = new Restaurant(); // Calls the default constructor favLunchPlace.print(); favLunchPlace.setName("Central Deli"); favLunchPlace.setRating(4); favLunchPlace.print(); } }

Abstract Classes

Definition: A class that cannot be instantiated as an object, but is the superclass for a subclass and specifies how the subclass must be implemented. Guides the design of the subclass. How are they used: Guides the design of the subclass.

Inheritance: Overriding Methods

Difference between Overriding and Overloading Override: A derived class may define a member method having the same name as the base class. Such a member method overrides the method of the base class. The overridden method can be accessed using the super keyword, such as: super.printItem(); Overloading:

Classes: Memory and Addressing

Difference between how primitives and objects are stored Issues with == (equals operator) when comparing objects

Casting doubles to ints

Ex: myInt = (int)myDouble The fractional part is truncated. Ex: 9.5 becomes 9

Input/Output: System.out.println

How it works: Differences: What is output?

Classes: Wrapper Class

How they work: a Wrapper class is a class whose objects wraps or contains a primitive data type. When we create an object to a wrapper class, it contains a field and in this field, we can store a primitive data type. In other words, we can wrap a primitive value into a wrapper class object. Recognize and understand code using them. Primitive data types: char, byte, short, long, float, double, boolean. // Java program to demonstrate Wrapping and UnWrapping // in Java Classes class WrappingUnwrapping { public static void main(String args[]) { // byte data type byte a = 1; // wrapping around Byte object Byte byteobj = new Byte(a); // int data type int b = 10; //wrapping around Integer object Integer intobj = new Integer(b); // float data type float c = 18.6f; // wrapping around Float object Float floatobj = new Float(c); // double data type double d = 250.5; // Wrapping around Double object Double doubleobj = new Double(d); // char data type char e='a'; // wrapping around Character object Character charobj=e; // printing the values from objects System.out.println("Values of Wrapper objects (printing as objects)"); System.out.println("Byte object byteobj: " + byteobj); System.out.println("Integer object intobj: " + intobj); System.out.println("Float object floatobj: " + floatobj); System.out.println("Double object doubleobj: " + doubleobj); System.out.println("Character object charobj: " + charobj); // objects to data types (retrieving data types from objects) // unwrapping objects to primitive data types byte bv = byteobj; int iv = intobj; float fv = floatobj; double dv = doubleobj; char cv = charobj; // printing the values from data types System.out.println("Unwrapped values (printing as data types)"); System.out.println("byte value, bv: " + bv); System.out.println("int value, iv: " + iv); System.out.println("float value, fv: " + fv); System.out.println("double value, dv: " + dv); System.out.println("char value, cv: " + cv); } } Output: Values of Wrapper objects (printing as objects) Byte object byteobj: 1 Integer object intobj: 10 Float object floatobj: 18.6 Double object doubleobj: 250.5 Character object charobj: a Unwrapped values (printing as data types) byte value, bv: 1 int value, iv: 10 float value, fv: 18.6 double value, dv: 250.5 char value, cv: a

Classes: Variables

Instance Variables: non-static variables and are declared in a class outside any method, constructor, or block. These are created when an object of the class is created and destroyed when the object is destroyed. Unlike local variables, we may use access specifiers for instance variables. Parameters: type of data Local Variables: A variable defined within a block or method or constructor. These are created when the block is entered or the function is called and destroyed after exiting from the function or block. The scope of these variables exists only within the block in which the variable is declared.

Inheritance: Object Class

Object class serves as the base class for all other classes and does not have a superclass - i.e., the Object class is located at the root of the Java class heirarchy. Thus, all classes, including user-defined classes, implement Object's methods. Top super class: Equals method: equals(otherObject) -- Compares an Object to another otherObject and returns true if both variables reference the same object. Otherwise, the equals() method returns false. By default, the equals() method tests the equality of the two Object references, not the equality of their contents.

Polymorphism

Polymorphism: refers to determining which program behavior to execute depending on data types. Compile Time: Method overloading is a form of this, wherein the compiler determines which of several identically name methods to call based on the method's arguments. Run Time: compiler cannot make the determination but instead the determination is made while the program is running.

Classes: Public and Private

Public Classes: A variable or method means that any class can access it. Private Classes: can only be accessed within the class that defined them in the first place. Access Specifiers(Modifiers): Access Specifiers regulate access to classes, fields, and methods. They determine whether a field or method in a class can be used or invoked by another method in another class or subclass. Protected variables and methods allow the class itself to access them, classes inside of the same package to access them, and subclasses of that class to access them. Let's say we define a protected method in Animal called eat(). Now, we can use it in the Dog class if Dog is a subclass of Animal (using extends). Also notice that a Chair is NOT a subclass of Animal and therefore has no access to the method.

Input/Output: Scanner Class

Purpose and Usage of: A scanner is a text parser that can get numbers, words, or phrases from an input source such as the keyboard. Create a scanner object: Scanner scnr = new Scanner(System.in); x = scnr.nextInt(); Purpose of "new" operator: What is System.in? Getting input is achieved by first creating a Scanner object via the statement: Scanner scnr = new Scanner(System.in); System.in corresponds to keyboard input. Then, given Scanner object scnr, the following statement gets an input value and assigns x with that value: x = scnr.nextInt(); Scanner methods: nextInt() scnr.nextInt(): Given Scanner object scnr, the following statement gets an input value and assigns x with that value: x = scnr.nextInt(). Sample Code: import java.util.Scanner; public class DogYears { public static void main(String [] args) { Scanner scnr = new Scanner(System.in); int dogYears; int humanYears; dogYears = scnr.nextInt(); humanYears = 7 * dogYears; System.out.print("A "); System.out.print(dogYears); System.out.print(" year old dog is about a "); System.out.print(humanYears); System.out.println(" year old human."); } }

Code Comprehension: Write Classes and Methods

Selection and Iteration (if, switch, while, do while, and for) Arrays (including an array of objects) Inheritance & Polymorphism: Overriding Methods: Call to super() class methods Abstract classes Create objects of different types Use polymorphism to call methods Throw and Catch Exceptions

Code Comprehension: Given Code

Show Output Show Value of Variables Fill in Missing Code Explain Code Operation Locate Errors in Code

Classes: Static Methods

Static: The keyword static indicates a variable is allocated in memory only once during a program's execution. Static field: A field of the class instead of a field of each class object. Static member method: A class method that is independent of class objects.

Flow of Control: "if" Statements

Structure/Syntax: if (x < 20) { System.out.println("X is less than 20"); } Compound Statements/Multiple Alternatives/ Nested Statement: How they work: a branch (program path) taken only if an expression is true. Does order matter?

Error Types and Definitions

Syntax Error: the violation of a programming language's rules on how symbols can be combined to create a program. Syntax errors are detected by the compiler. Compile-Time Error: Because a syntax error is detected by the compiler, a syntax error is known as one type of compile-time error. *Side note: Compilers were created by programmers to support high level languages. Compilers are actually programs that automatically translate high level language programs into executable programs. Logic Error: Also called a bug, is an error that occurs while a program runs. Run-Time Error:

Classes: "this" keyword

This: Within a member method, the implicitly-passed object reference is accessible via the keyword this. In particular, a class member can be access as this.classMember ShapeSquare.java: public class ShapeSquare { // Private fields private double sideLength; // Public methods public void setSideLength(double sideLength) { this.sideLength = sideLength; // Field member Parameter } public double getArea() { return sideLength * sideLength; // Both refer to field } } ShapeTest.java: public class ShapeTest { public static void main(String[] args) { ShapeSquare square1 = new ShapeSquare(); square1.setSideLength(1.2); System.out.println("Square's area: " + square1.getArea()); } } OUTPUT: Square's area: 1.44

Classes: Packages

What are they? How and why are they useful?

Classes: Javadoc

What is it? Javadoc is a tool that parses specially formatted multi-line comments to generate program documentation in HTML format. How and why is it used? Recognize it. @author @version @param @return @see

Escapes Sequences

\n = newline \t = tab

Assignment Operator

assigns the value of the expression on its right to the variable on its left. "="

Strings

charAt: the notation someString.chatAt(x) determines the character at index x of a string. Ex: Given userString is "Run!" then x = userString.charAt(0); //returns R concatenation: S1.concat(s2) returns a new string that appends s2 to s1 Ex: if s1 is "Hey", then s1.concat("!!!") returns "Hey!!!" toUpperCase: toUpperCase('a') //returns A toLowerCase: toLowerCase('A') // returns a: indexOf: if userText is "Help me!" userText.indexOf('p') //returns 3 userText.indexOf('e') //returns 1 (first occurence) userText.indexOf('z') // returns -1 (because z isn't in text) userText.indexOf("me") // Returns 5 userText.indexOf('e', 2) // Returns 6 (starts at index 2) userText.lastIndexOf('e') // Returns 6 (last occurrence) substring: // userText is "http://google.com" userText.substring(0, 7) // Returns "http://" userText.substring(13, 17) // Returns ".com" // Returns last 4: ".com" userText.substring(userText.length() - 4, userText.length())

object-oriented programming

designing a program by discovering objects, their properties, and their relationships

Inheritance: Changing Return Type

https://thispointer.com/overriding-a-method-with-different-return-type-in-java/ package com.thispointer.inheritance.example1; class Base { public Object display(String obj) { System.out.println("Base.display() " + obj); return "0"; } } class Derived extends Base { @Override public String display(String obj) { System.out.println("Derived.display() " + obj); return "Derived"; } } public class Example { public static void main(String[] args) { Base baseRef = new Derived(); // Due to dynamic binding, will call the derived class // display() function String data = (String)baseRef.display("test"); System.out.println(data); } } Output: Derived.display() test Derived

Code Comp: Selection switch()

import java.util.Scanner; // Needed for the Scanner class /** This program demonstrates a switch statement. */ public class PetFood { public static void main(String[] args) { String input; // To hold the user's input char foodGrade; // Grade of pet food // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Prompt the user for a grade of pet food. System.out.println("Our pet food is available in " + "three grades:"); System.out.print("A, B, and C. Which do you want " + "pricing for? "); input = keyboard.nextLine(); foodGrade = input.charAt(0); // Display pricing for the selected grade. switch(foodGrade) { case 'a': case 'A': System.out.println("30 cents per lb."); break; case 'b': case 'B': System.out.println("20 cents per lb."); break; case 'c': case 'C': System.out.println("15 cents per lb."); break; default: System.out.println("Invalid choice."); } } }

Code Comp: Selection - "if else"

import java.util.Scanner; // Needed for the Scanner class /** This program demonstrates the if-else statement. */ public class Division { public static void main(String[] args) { double number1, number2; // Division operands double quotient; // Result of division // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Get the first number. System.out.print("Enter a number: "); number1 = keyboard.nextDouble(); // Get the second number. System.out.print("Enter another number: "); number2 = keyboard.nextDouble(); if (number2 == 0) { System.out.println("Division by zero is not possible."); System.out.println("Please run the program again and "); System.out.println("enter a number other than zero."); } else { quotient = number1 / number2; System.out.print("The quotient of " + number1); System.out.print(" divided by " + number2); System.out.println(" is " + quotient); } } }

Code Comp: Selection - "if"

import javax.swing.JOptionPane; // Needed for JOptionPane /** This program demonstrates the if statement. */ public class AverageScore { public static void main(String[] args) { double score1; // To hold score #1 double score2; // To hold score #2 double score3; // To hold score #3 double average; // To hold the average score String input; // To hold the user's input // Get the first test score. input = JOptionPane.showInputDialog("Enter score #1:"); score1 = Double.parseDouble(input); // Get the second score. input = JOptionPane.showInputDialog("Enter score #2:"); score2 = Double.parseDouble(input); // Get the third test score. input = JOptionPane.showInputDialog("Enter score #3:"); score3 = Double.parseDouble(input); // Calculate the average score. average = (score1 + score2 + score3) / 3.0; // Display the average score. JOptionPane.showMessageDialog(null, "The average is " + average); // If the score was greater than 95, let the user know // that's a great score. if (average > 95) JOptionPane.showMessageDialog(null, "That's a great score!"); System.exit(0); } }

Code Comp: Selection - "nested if"

import javax.swing.JOptionPane; // Needed for JOptionPane class /** This program demonstrates a nested if statement. **/ public class LoanQualifier { public static void main(String[] args) { double salary; // Annual salary double yearsOnJob; // Years at current job String input; // To hold string input // Get the user's annual salary. input = JOptionPane.showInputDialog("Enter your " + "annual salary."); salary = Double.parseDouble(input); // Get the number of years at the current job. input = JOptionPane.showInputDialog("Enter the number of " + "years at your current job."); yearsOnJob = Double.parseDouble(input); // Determine whether the user qualifies for the loan. if (salary >= 30000) { if (yearsOnJob >= 2) { JOptionPane.showMessageDialog(null, "You qualify " + "for the loan."); } else { JOptionPane.showMessageDialog(null, "You must have " + "been on your current job for at least " + "two years to qualify."); } } else { JOptionPane.showMessageDialog(null, "You must earn " + "at least $30,000 per year to qualify."); } System.exit(0); } }

Code Comp: Selection && operator

import javax.swing.JOptionPane; // Needed for JOptionPane class /** This program demonstrates the logical && operator. */ public class LogicalAnd { public static void main(String[] args) { double salary; // Annual salary double yearsOnJob; // Years at current job String input; // To hold string input // Get the user's annual salary. input = JOptionPane.showInputDialog("Enter your " + "annual salary."); salary = Double.parseDouble(input); // Get the number of years at the current job. input = JOptionPane.showInputDialog("Enter the number of " + "years at your current job."); yearsOnJob = Double.parseDouble(input); // Determine whether the user qualifies for the loan. if (salary >= 30000 && yearsOnJob >= 2) { JOptionPane.showMessageDialog(null, "You qualify " + "for the loan."); } else { JOptionPane.showMessageDialog(null, "You do not " + "qualify for the loan."); } System.exit(0); } }

Code Comp: Selection || operator

import javax.swing.JOptionPane; // Needed for JOptionPane class /** This program demonstrates the logical || operator. */ public class LogicalOr { public static void main(String[] args) { double salary; // Annual salary double yearsOnJob; // Years at current job String input; // To hold string input // Get the user's annual salary. input = JOptionPane.showInputDialog("Enter your " + "annual salary."); salary = Double.parseDouble(input); // Get the number of years at the current job. input = JOptionPane.showInputDialog("Enter the number of " + "years at your current job."); yearsOnJob = Double.parseDouble(input); // Determine whether the user qualifies for the loan. if (salary >= 30000 || yearsOnJob >= 2) { JOptionPane.showMessageDialog(null, "You qualify " + "for the loan."); } else { JOptionPane.showMessageDialog(null, "You do not " + "qualify for the loan."); } System.exit(0); } }

Remainder Operator (%)

performs division and returns the remainder AKA Modulo Operator Ex: 23 % 10 is 3

Code Comp: Selection equals()

public class StringCompare { public static void main(String [] args) { String name1 = "Mark", name2 = "Mark", name3 = "Mary"; // Compare "Mark" and "Mark" if (name1.equals(name2)) { System.out.println(name1 + " and " + name2 + " are the same."); } else { System.out.println(name1 + " and " + name2 + " are the NOT the same."); } // Compare "Mark" and "Mary" if (name1.equals(name3)) { System.out.println(name1 + " and " + name3 + " are the same."); } else { System.out.println(name1 + " and " + name3 + " are the NOT the same."); } } }

Classes: Static Variables

static data_type variable_name; A static variable is common to all the instances (or objects) of the class because it is a class level variable. In other words, you can say that only a single copy of the static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.

Inheritance: Super keyword

super() When to use: used inside a subclass method definition to call a method defined in the super class. It is also used by class constructors to invoke constructors of its parent class. Private methods of the superclass cannot be called. How to use: With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.


Conjuntos de estudio relacionados

Immunology - Self and non-self recognition

View Set

California Property & Casualty Exam (2023)

View Set

Biology Exam 3 mastering Biology

View Set

N317 - Pharmacology Exam 2 Practice Questions

View Set