Exam 1 CS-1440 Java Programming Intro

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

How to use printf to nicely format output

A printf format reference page (cheat sheet) By Alvin Alexander. Last updated: December 18 2018 Table of Contents printf formatting with Perl and Java A summary of printf format specifiers Controlling integer width with printf Left-justifying printf integer output The printf integer zero-fill option printf integer formatting formatting floating point numbers with printf printf string formatting printf special characters Related printf content Summary: This page is a printf formatting cheat sheet. I originally created this cheat sheet for my own purposes, and then thought I would share it here. A great thing about the printf formatting syntax is that the format specifiers you can use are very similar — if not identical — between different languages, including C, C++, Java, Perl, PHP, Ruby, Scala, and others. This means that your printf knowledge is reusable, which is a good thing. printf formatting with Perl and Java In this cheat sheet I'll show all the examples using Perl, but at first it might help to see one example using both Perl and Java. Therefore, here's a simple Perl printf example to get things started: printf("the %s jumped over the %s, %d times", "cow", "moon", 2); And here are three different Java printf examples, using different string formatting methods that are available to you in the Java programming language: System.out.format("the %s jumped over the %s, %d times", "cow", "moon", 2); System.err.format("the %s jumped over the %s, %d times", "cow", "moon", 2); String result = String.format("the %s jumped over the %s, %d times", "cow", "moon", 2); As you can see in that last String.format example, that line of code doesn't print any output, while the first line prints to standard output, and the second line prints to standard error. In the remainder of this document I'll use Perl examples, but again, the actual format specifier strings can be used in many different languages. A summary of printf format specifiers Here's a quick summary of the available printf format specifiers: %c character %d decimal (integer) number (base 10) %e exponential floating-point number %f floating-point number %i integer (base 10) %o octal number (base 8) %s a string of characters %u unsigned decimal (integer) number %x number in hexadecimal (base 16) %% print a percent sign \% print a percent sign Controlling integer width with printf The %3d specifier is used with integers, and means a minimum width of three spaces, which, by default, will be right-justified: printf("%3d", 0); 0 printf("%3d", 123456789); 123456789 printf("%3d", -10); -10 printf("%3d", -123456789); -123456789 Left-justifying printf integer output To left-justify integer output with printf, just add a minus sign (-) after the % symbol, like this: printf("%-3d", 0); 0 printf("%-3d", 123456789); 123456789 printf("%-3d", -10); -10 printf("%-3d", -123456789); -123456789 The printf integer zero-fill option To zero-fill your printf integer output, just add a zero (0) after the % symbol, like this: printf("%03d", 0); 000 printf("%03d", 1); 001 printf("%03d", 123456789); 123456789 printf("%03d", -10); -10 printf("%03d", -123456789); -123456789 printf integer formatting As a summary of printf integer formatting, here's a little collection of integer formatting examples. Several different options are shown, including a minimum width specification, left-justified, zero-filled, and also a plus sign for positive numbers. Description Code Result At least five wide printf("'%5d'", 10); ' 10' At least five-wide, left-justified printf("'%-5d'", 10); '10 ' At least five-wide, zero-filled printf("'%05d'", 10); '00010' At least five-wide, with a plus sign printf("'%+5d'", 10); ' +10' Five-wide, plus sign, left-justified printf("'%-+5d'", 10); '+10 ' formatting floating point numbers with printf Here are several examples showing how to format floating-point numbers with printf: Description Code Result Print one position after the decimal printf("'%.1f'", 10.3456); '10.3' Two positions after the decimal printf("'%.2f'", 10.3456); '10.35' Eight-wide, two positions after the decimal printf("'%8.2f'", 10.3456); ' 10.35' Eight-wide, four positions after the decimal printf("'%8.4f'", 10.3456); ' 10.3456' Eight-wide, two positions after the decimal, zero-filled printf("'%08.2f'", 10.3456); '00010.35' Eight-wide, two positions after the decimal, left-justified printf("'%-8.2f'", 10.3456); '10.35 ' Printing a much larger number with that same format printf("'%-8.2f'", 101234567.3456); '101234567.35' printf string formatting Here are several examples that show how to format string output with printf: Description Code Result A simple string printf("'%s'", "Hello"); 'Hello' A string with a minimum length printf("'%10s'", "Hello"); ' Hello' Minimum length, left-justified printf("'%-10s'", "Hello"); 'Hello ' printf special characters The following character sequences have a special meaning when used as printf format specifiers: \a audible alert \b backspace \f form feed \n newline, or linefeed \r carriage return \t tab \v vertical tab \\ backslash As you can see from that last example, because the backslash character itself is treated specially, you have to print two backslash characters in a row to get one backslash character to appear in your output. Here are a few examples of how to use these special characters: Description Code Result Insert a tab character in a string printf("Hello\tworld"); Hello world Insert a newline character in a string printf("Hello\nworld"); Hello world Typical use of the newline character printf("Hello world\n"); Hello world A DOS/Windows path with backslash characters printf("C:\\Windows\\System32\\"); C:\Windows\System32\

What scope is, and how to identify the scope of variables and other entities in your programs

Scope Rules Since a main program could contain many functions and in fact a function can contain other functions (i.e., nested functions), one may ask the following questions: Could a function use a variable declared in the main program? Could a main program use a variable declared in one of its function? The scope rules answer these questions. In fact, scope rules tell us if an entity (i.e., variable, parameter and function) is "visible" or accessible at certain places. Thus, places where an entity can be accessed or visible is referred to the scope of that entity. The simplest rule is the following: Scope Rule 1 The scope of an entity is the program or function in which it is declared. Therefore, in the following, the scope of parameter PI and variables m and n is the main program, the scope of formal argument k and REAL variables f and g is function Funct1(), and the scope of formal arguments u and v is function Funct2(). PROGRAM Scope_1 IMPLICIT NONE REAL, PARAMETER :: PI = 3.1415926 INTEGER :: m, n ................... CONTAINS INTEGER FUNCTION Funct1(k) IMPLICIT NONE INTEGER, INTENT(IN) :: k REAL :: f, g .......... END FUNCTION Funct1 REAL FUNCTION Funct2(u, v) IMPLICIT NONE REAL, INTENT(IN) :: u, v .......... END FUNCTION Funct2 END PROGRAM Scope_1 There is a direct consequence of Scope Rule 1. Since an entity declared in a function has a scope of that function, this entity cannot be seen from outside of the function. In the above example, formal argument k and variables f and g are declared within function Funct1(), they are only "visible" in function Funct1() and are not visible outside of Funct1(). In other words, since k, f and g are not "visible" from the main program and function Funct2(), they cannot be used in the main program and function Funct2(). Similarly, the main program and function Funct1() cannot use the formal arguments u and v and any entity declared in function Funct2(). Local Entities Due to the above discussion, the entities declared in a function or in the main program are said local to that function or the main program. Thus, k, f and g are local to function Funct1(), u and v are local to function Funct2(), and PI, m and n are local to the main program. Global Entities Given a function f(), entities that are declared in all containing functions or the main program are said global to f(). In the above example, since variables m and n are declared in the main program, they are global to Funct1() and function Funct2(). However, variables f and g are not global to function Funct2(), since Funct1() does not contain Funct2(). Similarly, formal arguments u and v are not global to function Funct1(). This comes the second scope rule: Scope Rule 2 A global entity is visible to all contained functions, including the function in which that entity is declared. Continue with the above example, since m and n are global to both functions Funct1() and Funct2(), they can be used in these two functions. PROGRAM Scope_2 IMPLICIT NONE INTEGER :: a = 1, b = 2, c = 3 WRITE(*,*) Add(a) c = 4 WRITE(*,*) Add(a) WRITE(*,*) Mul(b,c) CONTAINS INTEGER FUNCTION Add(q) IMPLICIT NONE INTEGER, INTENT(IN) :: q Add = q + c END FUNCTION Add INTEGER FUNCTION Mul(x, y) IMPLICIT NONE INTEGER, INTENT(IN) :: x, y Mul = x * y END FUNCTION Mul END PROGRAM Scope_2 In the above program, variables a, b and c are global to both functions Add() and Mul(). Therefore, since variable c used in function Add() is global to Add(), expression q + c means computing the sum of the value of the formal argument q and the value of global variable c. Therefore, the first WRITE produces 4 (= 1 + 3). Before the second WRITE, the value of c is changed to 4 in the main program. Hence, the second WRITE produces 5 (= 1 + 4). The third WRITE produces 8 (= 2 * 4). Thus, the first two WRITEs produce different results even though their actual arguments are the same! This is usually refereed to as a side effect. Therefore, if it is possible, avoid using global variables in internal functions. Let us continue with the above example. To remove side effect, one could add one more argument to function Add() for passing the value of c. PROGRAM Scope_2 IMPLICIT NONE INTEGER :: a = 1, b = 2, c = 3 WRITE(*,*) Add(a, c) c = 4 WRITE(*,*) Add(a, c) WRITE(*,*) Mul(b,c) CONTAINS INTEGER FUNCTION Add(q, h) IMPLICIT NONE INTEGER, INTENT(IN) :: q, h Add = q + h END FUNCTION Add INTEGER FUNCTION Mul(x, y) IMPLICIT NONE INTEGER, INTENT(IN) :: x, y Mul = x * y END FUNCTION Mul END PROGRAM Scope_2 What If There Are Name Conflicts? Frequently we may have a local entity whose name is identical to the name of a global entity. To resolve this name conflict, we need the following new scope rule: Scope Rule 3 An entity declared in the scope of another entity is always a different entity even if their names are identical. In the program below, the main program declares a variable i, which is global to function Sum(). However, i is also declared in function Sum(). According to Scope Rule 3 above, these two is are two different entities. More precisely, when the value of Sum()'s i is changed, this change will not affect the i in the main program and vice versa. This would save us a lot of time in finding variables with different names. PROGRAM Scope_3 IMPLICIT NONE INTEGER :: i, Max = 5 DO i = 1, Max Write(*,*) Sum(i) END DO CONTAINS INTEGER FUNCTION Sum(n) IMPLICIT NONE INTEGER, INTENT(IN) :: n INTEGER :: i, s s = 0 DO i = 1, n s = s + i END DO Sum = s END FUNCTION Sum END PROGRAM Scope_3

What a boolean flag is.

A Boolean value is one with two choices: true or false, yes or no, 1 or 0. In Java, there is a variable type for Boolean values: boolean user = true; So instead of typing int or double or string, you just type boolean (with a lower case "b").

What the difference between a statement and expression is.

It's a very subtle difference, but once someone understands it, he/she automatically understands the real value of functional programming. Expressions have a value, while statements do not. If you can pass it as an argument to a function, it's an expression. If you can't, it's a statement.

What the arithmetic operators are, and how they work at each data type.

Arithmetic Operators The Java programming language supports various arithmetic operators for all floating-point and integer numbers. These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo). The following table summarizes the binary arithmetic operations in the Java programming language. Operator Use Description + op1 + op2 Adds op1 and op2; also used to concatenate strings - op1 - op2 Subtracts op2 from op1 * op1 * op2 Multiplies op1 by op2 / op1 / op2 Divides op1 by op2 % op1 % op2 Computes the remainder of dividing op1 by op2 Here's an example program, ArithmeticDemo (in a .java source file), that defines two integers and two double-precision floating-point numbers and uses the five arithmetic operators to perform different arithmetic operations. This program also uses + to concatenate strings. The arithmetic operations are shown in boldface: public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37; int j = 42; double x = 27.475; double y = 7.22; System.out.println("Variable values..."); System.out.println(" i = " + i); System.out.println(" j = " + j); System.out.println(" x = " + x); System.out.println(" y = " + y); //adding numbers System.out.println("Adding..."); System.out.println(" i + j = " + (i + j)); System.out.println(" x + y = " + (x + y)); //subtracting numbers System.out.println("Subtracting..."); System.out.println(" i - j = " + (i - j)); System.out.println(" x - y = " + (x - y)); //multiplying numbers System.out.println("Multiplying..."); System.out.println(" i * j = " + (i * j)); System.out.println(" x * y = " + (x * y)); //dividing numbers System.out.println("Dividing..."); System.out.println(" i / j = " + (i / j)); System.out.println(" x / y = " + (x / y)); //computing the remainder resulting from dividing numbers System.out.println("Computing the remainder..."); System.out.println(" i % j = " + (i % j)); System.out.println(" x % y = " + (x % y)); //mixing types System.out.println("Mixing types..."); System.out.println(" j + y = " + (j + y)); System.out.println(" i * x = " + (i * x)); } } The output from this program is: Variable values... i = 37 j = 42 x = 27.475 y = 7.22 Adding... i + j = 79 x + y = 34.695 Subtracting... i - j = -5 x - y = 20.255 Multiplying... i * j = 1554 x * y = 198.37 Dividing... i / j = 0 x / y = 3.8054 Computing the remainder... i % j = 37 x % y = 5.815 Mixing types... j + y = 49.22 i * x = 1016.58 Note that when an integer and a floating-point number are used as operands to a single arithmetic operation, the result is floating point. The integer is implicitly converted to a floating-point number before the operation takes place. The following table summarizes the data type returned by the arithmetic operators, based on the data type of the operands. The necessary conversions take place before the operation is performed. Data Type of Result Data Type of Operands long Neither operand is a float or a double (integer arithmetic); at least one operand is a long. int Neither operand is a float or a double (integer arithmetic); neither operand is a long. double At least one operand is a double. float At least one operand is a float; neither operand is a double. In addition to the binary forms of + and -, each of these operators has unary versions that perform the following operations, as shown in the next table: Operator Use Description + +op Promotes op to int if it's a byte, short, or char - -op Arithmetically negates op Two shortcut arithmetic operators are ++, which increments its operand by 1, and --, which decrements its operand by 1. Either ++ or -- can appear before (prefix) or after (postfix) its operand. The prefix version, ++op/--op, evaluates to the value of the operand after the increment/decrement operation. The postfix version, op++/op--, evaluates to the value of the operand before the increment/decrement operation. The following program, called SortDemo (in a .java source file) , uses ++ twice and -- once. public class SortDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = arrayOfInts.length; --i >= 0; ) { for (int j = 0; j < i; j++) { if (arrayOfInts[j] > arrayOfInts[j+1]) { int temp = arrayOfInts[j]; arrayOfInts[j] = arrayOfInts[j+1]; arrayOfInts[j+1] = temp; } } } for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); } } This program puts ten integer values into an array — a fixed-length structure that can hold multiple values of the same type — then sorts them. The boldface line of code declares an array referred to by arrayOfInts, creates the array, and puts ten integer values into it. The program uses arrayOfInts.length to get the number of elements in the array. Individual elements are accessed with this notation: arrayOfInts[index], where index is an integer indicating the position of the element within the array. Note that indices begin at 0. You'll get more details and examples for arrays in the section Arrays (in the Learning the Java Language trail). The output from this program is a list of numbers sorted from lowest to highest: 3 8 12 32 87 127 589 622 1076 2000 Let's look at how the SortDemo program uses -- to help control the outer of its two nested sorting loops. Here's the statement that controls the outer loop: for (int i = arrayOfInts.length; --i >= 0; ) { ... } The for statement is a looping construct, which you'll meet later in this chapter. What's important here is the code in boldface, which continues the for loop as long as the value returned by --i is greater than or equal to 0. Using the prefix version of -- means that the last iteration of this loop occurs when i is equal to 0. If we change the code to use the postfix version of --, the last iteration of this loop occurs when i is equal to -1, which is incorrect for this program because i is used as an array index and -1 is not a valid array index. The other two loops in the program use the postfix version of ++. In both cases, the version used doesn't really matter, because the value returned by the operator isn't used for anything. When the return value of one of these shortcut operations isn't used for anything, convention prefers the postfix version. The shortcut increment/decrement operators are summarized in the following table. Operator Use Description ++ op++ Increments op by 1; evaluates to the value of op before it was incremented ++ ++op Increments op by 1; evaluates to the value of op after it was incremented -- op-- Decrements op by 1; evaluates to the value of op before it was decremented -- --op Decrements op by 1; evaluates to the value of op after it was decremented Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search Feedback Form

- The difference between a variable and a literal

A literal is notation for representing a fixed ( const ) value. A variable is storage location associated with a symbolic name (pointed to, if you'd like). In any programming language a Literal is a constant value, where as identifiers can change their values. Identifiers can store literals and process them further.

What a class definition is and how to write one

How to define class in Python? The key concept in this programming paradigm is classes. In Python, these are used to create objects which can have attributes. Objects are specific instances of a class. A class is essentially a blueprint of what an object is and how it should behave.

How to write a switch statement.

The switch Statement Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings). The following code example, SwitchDemo, declares an int named month whose value represents a month. The code displays the name of the month, based on the value of month, using the switch statement. public class SwitchDemo { public static void main(String[] args) { int month = 8; String monthString; switch (month) { case 1: monthString = "January"; break; case 2: monthString = "February"; break; case 3: monthString = "March"; break; case 4: monthString = "April"; break; case 5: monthString = "May"; break; case 6: monthString = "June"; break; case 7: monthString = "July"; break; case 8: monthString = "August"; break; case 9: monthString = "September"; break; case 10: monthString = "October"; break; case 11: monthString = "November"; break; case 12: monthString = "December"; break; default: monthString = "Invalid month"; break; } System.out.println(monthString); } } In this case, August is printed to standard output. The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label. You could also display the name of the month with if-then-else statements: int month = 8; if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); } ... // and so on Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing. An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object. Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered. The program SwitchDemoFallThrough shows statements in a switch block that fall through. The program displays the month corresponding to the integer month and the months that follow in the year: public class SwitchDemoFallThrough { public static void main(String[] args) { java.util.ArrayList<String> futureMonths = new java.util.ArrayList<String>(); int month = 8; switch (month) { case 1: futureMonths.add("January"); case 2: futureMonths.add("February"); case 3: futureMonths.add("March"); case 4: futureMonths.add("April"); case 5: futureMonths.add("May"); case 6: futureMonths.add("June"); case 7: futureMonths.add("July"); case 8: futureMonths.add("August"); case 9: futureMonths.add("September"); case 10: futureMonths.add("October"); case 11: futureMonths.add("November"); case 12: futureMonths.add("December"); break; default: break; } if (futureMonths.isEmpty()) { System.out.println("Invalid month number"); } else { for (String monthName : futureMonths) { System.out.println(monthName); } } } } This is the output from the code: August September October November December Technically, the final break is not required because flow falls out of the switch statement. Using a break is recommended so that modifying the code is easier and less error prone. The default section handles all values that are not explicitly handled by one of the case sections. The following code example, SwitchDemo2, shows how a statement can have multiple case labels. The code example calculates the number of days in a particular month: class SwitchDemo2 { public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0)) numDays = 29; else numDays = 28; break; default: System.out.println("Invalid month."); break; } System.out.println("Number of Days = " + numDays); } } This is the output from the code: Number of Days = 29 Using Strings in switch Statements In Java SE 7 and later, you can use a String object in the switch statement's expression. The following code example, StringSwitchDemo, displays the number of the month based on the value of the String named month: public class StringSwitchDemo { public static int getMonthNumber(String month) { int monthNumber = 0; if (month == null) { return monthNumber; } switch (month.toLowerCase()) { case "january": monthNumber = 1; break; case "february": monthNumber = 2; break; case "march": monthNumber = 3; break; case "april": monthNumber = 4; break; case "may": monthNumber = 5; break; case "june": monthNumber = 6; break; case "july": monthNumber = 7; break; case "august": monthNumber = 8; break; case "september": monthNumber = 9; break; case "october": monthNumber = 10; break; case "november": monthNumber = 11; break; case "december": monthNumber = 12; break; default: monthNumber = 0; break; } return monthNumber; } public static void main(String[] args) { String month = "August"; int returnedMonthNumber = StringSwitchDemo.getMonthNumber(month); if (returnedMonthNumber == 0) { System.out.println("Invalid month"); } else { System.out.println(returnedMonthNumber); } } } The output from this code is 8. The String in the switch expression is compared with the expressions associated with each case label as if the String.equals method were being used. In order for the StringSwitchDemo example to accept any month regardless of case, month is converted to lowercase (with the toLowerCase method), and all the strings associated with the case labels are in lowercase. Note: This example checks if the expression in the switch statement is null. Ensure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.

- The sense in which constructors often perform "set up" tasks.

Ask Question 19 22 What is the purpose of a constructor? I've been learning Java in school and it seems to me like a constructor is largely redundant in things we've done thus far. It remains to be seen if a purpose comes about, but so far it seems meaningless to me. For example, what is the difference between the following two snippets of code? public class Program { public constructor () { function(); } private void function () { //do stuff } public static void main(String[] args) { constructor a = new constructor(); } } This is how we were taught do to things for assignments, but wouldn't the below do the same deal? public class Program { public static void main(String[] args) { function(); } private void function() { //do stuff } } The purpose of a constructor escapes me, but then again everything we've done thus far has been extremely rudimentary. java function methods constructor shareimprove this question asked Nov 12 '13 at 23:06 gator 1,40962150 5 That is not a constructor. In fact, it doesn't even construct the class at all. A constructor would look like public Program(){\\..., and would be invoked new Program(). - AJMansfield Nov 13 '13 at 0:54 add a comment 13 Answers active oldest votes 45 Constructors are used to initialize the instances of your classes. You use a constructor to create new objects often with parameters specifying the initial state or other important information about the object From the official Java tutorial: A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor: public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } To create a new Bicycle object called myBike, a constructor is called by the new operator: Bicycle myBike = new Bicycle(30, 0, 8); new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields. Although Bicycle only has one constructor, it could have others, including a no-argument constructor: public Bicycle() { gear = 1; cadence = 10; speed = 0; } Bicycle yourBike = new Bicycle(); invokes the no-argument constructor to create a new Bicycle object called yourBike. shareimprove this answer edited Jun 7 '16 at 12:14 Pshemo 95.1k15131192 answered Nov 12 '13 at 23:08 LotusUNSW 1,6641220 11 Either you haven't understood him, or he doesn't understand what constructors are useful for either. Let's say your program is a card game: you would like 52 instances of a class named Card, each having a number and a color. A constructor is used to create an instance of the class Card. And you'll need to call it 52 times to have 52 cards: new Card(1, "hearts"), etc. Now each instance of Player (you also need a constructor for that), can have a List (constructed using a constructor) of cards. Read an introductory Java book, or the official Java tutorial. - JB Nizet Nov 12 '13 at 23:12 2 Cheers, this cleared up my confusion. It makes sense for setting default or initial parameters, but in everything we've done so far, this wasn't needed. I guess we were being prepped for when it is required to maintain consistency. - gator Nov 12 '13 at 23:26 2 Whoever downvoted me, care to explain why? From my answer, I'm definitely not harming the OP's knowledge of constructors in any way. :/ - LotusUNSW Nov 12 '13 at 23:28 2 @LotusUNSW I have a feeling there's a downvoter-troll around here. Your answer's great. - Paul Richter Nov 13 '13 at 0:21 2 @AJMansfield - Not true. You can put additional constructors in a superclass and still use a default constructor in a subclass, as long as the superclass includes an explicit, accessible constructor with no arguments and no throws clause. A class can contain more than one constructor. The choice of constructors to provide can be based on what sets of parameters can be used to initialize an instance. Sometimes those parameters must be specified in a constructor, because they're invariant in the instance. - Andy Thomas Aug 19 '15 at 16:17 show 3 more comments 29 A constructor is basically a method that you can use to ensure that objects of your class are born valid. This is the main motivation for a constructor. Let's say you want your class has a single integer field that should be always larger than zero. How do you do that in a way that is reliable? public class C { private int number; public C(int number) { setNumber(number); } public void setNumber(int number) { if (number < 1) { throws IllegalArgumentException("C cannot store anything smaller than 1"); } this.number = number; } } In the code above, it may look like you are doing something redundant, but in fact you are ensuring that the number is always valid no matter what. "initialize the instances of a class" is what a constructor does, but not the reason why we have constructors. The question is about the purpose of a constructor. You can also initialize instances of a class externally, using c.setNumber(10) in the example above. So a constructor is not the only way to initialize instances. The constructor does that but in a way that is safe. In other words, a class alone solves the whole problem of ensuring their objects are always in valid states. Not using a constructor will leave such validation to the outside world, which is bad design. Here is another example: public class Interval { private long start; private long end; public Interval(long start, long end) { changeInterval(start, end); } public void changeInterval(long start, long end) { if (start >= end) { throw new IllegalArgumentException("Invalid interval."); } this.start = start; this.end = end; } public long duration() { return end - start; } } The Interval class represents a time interval. Time is stored using long. It does not make any sense to have an interval that ends before it starts. By using a constructor like the one above it is impossible to have an instance of Interval at any given moment anywhere in the system that stores an interval that does not make sense. shareimprove this answer edited Nov 13 '13 at 1:04 answered Nov 12 '13 at 23:15 Akira 2,4691117 In general, Constructors (of non-final classes) should call only final or private methods. stackoverflow.com/questions/4893558/... - shiggity Jun 1 '15 at 18:40 4 +1 for the pragmatic answer. This answer satisfied not only the definition, but also my WHY inquire. "To be born valid" was the small piece of "usefulness" that i was missing to inteprid the necessity to use constructors. - Arthur Zennig May 5 '16 at 17:43 I know this is extremely old, but is this a good way of thinking about "why". Lets say you make a contact list application. You hold addresses of 100 contacts, and a constructor to hold "valid" phone numbers. Every member is being initialised with a valid phone number? - someguy76 Feb 12 '18 at 15:01 Correct. If you represent phone numbers as classes or a field of an address class, you may want to validate a phone number before you create an object that holds such information. Think of objects as things that will not be necessarily under your strict control after its creation. Your object may, for instance, end up being used by code that you did not write. So your objects should mean something. A constructor is a way to say that no object is allowed to exist in a way that violates its semantics. - Akira Feb 14 '18 at 0:25 add a comment 9 As mentioned in LotusUNSW answer Constructors are used to initialize the instances of a class. Example: Say you have an Animal class something like class Animal{ private String name; private String type; } Lets see what happens when you try to create an instance of Animal class, say a Dog named Puppy. Now you have have to initialize name = Puppy and type = Dog. So, how can you do that. A way of doing it is having a constructor like Animal(String nameProvided, String typeProvided){ this.name = nameProvided; this.type = typeProvided; } Now when you create an object of class Animal, something like Animal dog = new Animal("Puppy", "Dog"); your constructor is called and initializes name and type to the values you provided i.e. Puppy and Dog respectively. Now you might ask what if I didn't provide an argument to my constructor something like Animal xyz = new Animal(); This is a default Constructor which initializes the object with default values i.e. in our Animal class name and type values corresponding to xyz object would be name = null and type = null shareimprove this answer answered Nov 12 '13 at 23:20 Prateek 1,5391820 2 +1 for a good answer. Clear and concise. Keep it up! - Choudhury Saadmaan Mahmid Aug 20 '14 at 6:46 add a comment 4 A constructor initializes an object when it is created . It has the same name as its class and is syntactically similar to a method , but constructor have no expicit return type.Typically , we use constructor to give initial value to the instance variables defined by the class , or to perform any other startup procedures required to make a fully formed object. Here is an example of constructor: class queen(){ int beauty; queen(){ beauty = 98; } } class constructor demo{ public static void main(String[] args){ queen arth = new queen(); queen y = new queen(); System.out.println(arth.beauty+" "+y.beauty); } } output is: 98 98 Here the construcor is : queen(){ beauty =98; } Now the turn of parameterized constructor. class queen(){ int beauty; queen(int x){ beauty = x; } } class constructor demo{ public static void main(String[] args){ queen arth = new queen(100); queen y = new queen(98); System.out.println(arth.beauty+" "+y.beauty); } } output is: 100 98 shareimprove this answer answered Jan 6 '16 at 13:46 Ashish Thapa 588 add a comment 3 Through a constructor (with parameters), you can 'ask' the user of that class for required dependencies. It is used to initialize instance variables and to pass up arguments to the constructor of a super class (super(...)), which basically does the same It can initialize (final) instance variables with code, that may throw Exceptions, as opposed to instance initializer scopes One should not blindly call methods from within the constructor, because initialization may not be finished/sufficient in the local or a derived class. shareimprove this answer edited May 23 '17 at 12:26 Community♦ 11 answered Nov 12 '13 at 23:11 Sam 7,05911839 Instance initializer scopes can throw exceptions, as long as all the constructors are declared to throw the same exceptions. - user207421 Oct 15 '15 at 2:43 add a comment 1 It's used to set up the contents and state of your class. Whilst it's true you can make the simpler example with the main method you only have 1 main method per app so it does not remain a sensible approach. Consider the main method to simply start your program and should know no more than how to do that. Also note that main() is static so cannot call functions that require a class instance and the state associated. The main method should call new Program().function() and the Program constructor should not call function() unless it is required for the setup of the class. shareimprove this answer answered Nov 12 '13 at 23:14 ajwillia.ms 39619 add a comment 1 The class definition defines the API for your class. In other words, it is a blueprint that defines the contract that exists between the class and its clients--all the other code that uses this class. The contract indicates which methods are available, how to call them, and what to expect in return. But the class definition is a spec. Until you have an actual object of this class, the contract is just "a piece of paper." This is where the constructor comes in. A constructor is the means of creating an instance of your class by creating an object in memory and returning a reference to it. Something that should happen in the constructor is that the object is in a proper initial state for the subsequent operations on the object to make sense. This object returned from the constructor will now honor the contract specified in the class definition, and you can use this object to do real work. Think of it this way. If you ever look at the Porsche website, you will see what it can do--the horsepower, the torque, etc. But it isn't fun until you have an actual Porsche to drive. Hope that helps. shareimprove this answer answered Nov 12 '13 at 23:21 Vidya 24.8k52851 add a comment 1 Constructor is basicaly used for initialising the variables at the time of creation of object shareimprove this answer answered Feb 24 '15 at 8:03 Praveen Srinivasan 83531738 add a comment 1 A Java constructor has the same name as the name of the class to which it belongs. Constructor's syntax does not include a return type, since constructors never return a value. Constructor is always called when object is created. example:- Default constructor class Student3{ int id; String name; void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } } Output: 0 null 0 null Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor. Example of parameterized constructor In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4{ int id; String name; Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } Output: 111 Karan 222 Aryan shareimprove this answer edited Oct 15 '15 at 2:33 Pang 6,9391664102 answered Mar 22 '15 at 12:44 Naresh Kumar 354313 2 There are some serious formatting issues in this post. Please edit to use code blocks. - Halvor Holsten Strand Mar 22 '15 at 13:04 add a comment 1 I thought a constructor might work like a database in which only it defines variables and methods to control them Then I saw objects that use variables and methods not defined in its constructor. So the discussion that makes the most sense to me is the one that tests variables values for validity, but the class can create variables and methods that are not defined in the constructor - less like a database and more like an over pressure valve on a steam locomotive. It doesn't control the wheels,etc. Far less of a definition than I thought. shareimprove this answer answered Jul 27 '16 at 21:59 user6646964 111 This doesn't answer the question - adao7000 Jul 27 '16 at 22:15 add a comment 1 Constructor will be helpful to prevent instances getting unreal values. For an example set a Person class with height , weight. There can't be a Person with 0m and 0kg shareimprove this answer edited Dec 11 '17 at 8:59 answered Sep 28 '17 at 3:21 rinjan 357416 add a comment 0 Well, first I will tell the errors in two code snippets. First code snippet public class Program { public constructor() // Error - Return type for the method is missing { function(); } private void function() { //do stuff } public static void main(String[] args) { constructor a = new constructor(); // Error - constructor cannot be resolved to a type } } As you can see the code above, constructor name is not same as class name. In the main() method you are creating a object from a method which has no return type. Second code snippet public class Program { public static void main(String[] args) { function(); // Error - Cannot make a static reference to the non-static method function() from the type Program } private void function() { //do stuff } } Now in this code snippet you're trying to create a static reference to the non-static method function() from the type Program, which is not possible. So the possible solution is this, First code snippet public class Program { public Program() { function(); } private void function() { //do stuff } public static void main(String[] args) { Program a = new Program(); a.function(); } } Second code snippet public class Program { public static void main(String[] args) { Program a = new Program(); a.function(); } private void function() { //do stuff } } Finally the difference between the code snippets is that, in first code snippet class name is not same as the class name While in the second code snippet there is no constructor defined. Meanwhile to understand the purpose of constructor refer resources below, https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Constructor.html http://www.flowerbrackets.com/learn-constructor-in-java/ http://www.flowerbrackets.com/java-constructor-example/ shareimprove this answer answered Nov 29 '17 at 13:36 Shiva 1895 add a comment 0 Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects. To understand clearly, see the below simple example: class Student { int sno,sage; String sname,dept; Student() { dept="CSE"; } public static void main(String a[]) { Student s1=new Student(); s1.sno=101; s1.sage=33; s1.sname="John"; Student s2=new Student(); s2.sno=102; s2.sage=99; s2.sname="Peter"; Student s3=new Student(); s3.sno=102; s3.sage=99; s3.sname="Peter"; System.out.println("The details of student1 are"); System.out.println("The student no is:"+s1.sno); System.out.println("The student age is:"+s1.sage); System.out.println("The student name is:"+s1.sname); System.out.println("The student dept is:"+s1.dept); System.out.println("The details of student2 are");`enter code here` System.out.println("The student no is:"+s2.sno); System.out.println("The student age is:"+s2.sage); System.out.println("The student name is:"+s2.sname); System.out.println("The student dept is:"+s2.dept); System.out.println("The details of student2 are"); System.out.println("The student no is:"+s3.sno); System.out.println("The student age is:"+s3.sage); System.out.println("The student name is:"+s3.sname); System.out.println("The student dept is:"+s3.dept); } } Output: The details of student1 are The student no is:101 The student age is:33 The student name is:John The student dept is:CSE The details of student2 are The student no is:102 The student age is:99 The student name is:Peter The student dept is:CSE The details of student2 are The student no is:102 The student age is:99 The student name is:Peter The student dept is:CSE

How to read a question carefully, and make sure your answer is an answer to the question asked.

How to Answer Top Java Interview Questions INDUSTRY SPECIFIC Hiring experts agree that Java is one of the most in-demand tech skills. But how do you get one of those hot jobs? First you have to artfully ace those pesky Java interview questions. We asked John Zukowski, an experienced Java pro who has also interviewed and hired many developers, to provide his expert advice on how to prepare for the most common Java interview questions. Interviewing for a Java-related job can be difficult. You might be going for a typical software development job, but the range of questions you can face makes the SATs seem easy. With this article, you will be better prepared to know the types of questions that you might run across, and more importantly, how to answer the questions, no matter what they are. With each release of the Java platform, the API set grows, thus, the range of potential Java interview questions grows regularly. List Java on your resume, and you can get asked a question on anything from the first to the last release. Add in the Enterprise and Micro Edition, and the API-related questions grow even further. Whether you're fresh out of school or someone who has been programming for a while, we'll prep you here for that next interview, as just knowing the API isn't all there is to the Java interview. The Java Job Interview The best way to prepare for your interview starts with having a realistic resume. If you put on your resume that you've used JDBC or Security, you better be prepared for someone to ask you a question about those technologies. The more specific a technology, like Hibernate, the higher the likelihood of getting asked a question about it, if it is a technology the company is interested in your specific experience. Don't put technologies on your resume that you think might help with automated keyword searches, but your exposure to the technologies is so sparse or non-existent that you can't answer a basic technical question about the technology. You will be expected to know computer science fundamentals. How much of that depends on your level. These computer science questions may actually be easier for the more beginning developer, as someone straight out of college might have just had a course on algorithms perhaps. Think data structures and performance-related here. The Interview Coding Test — How to Work the White Board java interview questions The more experienced you are, the more you will be expected to know how to code AND how to read code. Expect to have to go to a white board and solve a problem. Get comfortable doing it. When coding the solution to a problem on a white board in a job interview, talk through your solution. It may seem obvious, but don't just code the whole solution silently and ask if the questioner has any questions when you are done. Don't just code a brute force solution. More than likely, that isn't what the questioner is looking for. Also, once completed, the interviewer could just move on to the next question. If not, you'll be taking up valuable time correcting to the right solution after, and more importantly, you might do it wrong. When responding to coding problems, there are a few guidelines to follow. Some may seem obvious, but all are worth reminding. Listen carefully to the questions. If you're unsure of a question, ask for clarification, don't just answer what you think the interviewer might be looking for. Don't make assumptions. If asked to code something like a binary search, don't just assume an array of numbers. Listen for hints. If your interviewer gives you a hint, don't miss it, but more importantly don't ignore it. They're trying to push you in the right direction to an answer. Questions About Computer Science Fundamentals The most common set of questions you'll face test your knowledge of computer science. Why do you pick one data structure over another? How do you code a particular algorithm? It might seem simple, but could you code binary search in the Java programming language? Here is the implementation of the algorithm from the java.util.Arrays class for an int array source: private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } First, could you code this off the top of your head? Second, do any lines look different than your knowledge of the algorithm? What does the ">>> 1" do? That's basically a divide by two operation. I would say doing "/ 2" would suffice there. The return value of "-(low +1)" gives the caller the insert position where to insert the new key, if they wanted to do that task. Ask your interviewer, -1 might suffice to say something isn't there. The "-(low + 1)" bit could be a great follow-on question from the interviewer after you get the coded algorithm properly. Don't assume after you have a successful solution you are done with that problem. Introductory Java Interview Questions java interview questions As your skill level increases, the questions you receive get more complicated. That doesn't excuse you from knowing the introductory questions, too, if you are more experienced. The obvious set of questions you'll be asked test your knowledge of the Java API. The range of questions you will be asked here is enormous. Fresh out of school, you might be asked about the different keywords in Java. Been around the block a few times, then write a regular expression that describes the format of an email address. I was once asked the latter question and I didn't even mention regular expressions on my resume. Here are a couple sample questions and answers of what to expect at this level. Sample Introductory Java Question 1 Describe what all the different parts of the main() method declaration mean. How to Answer The first thing you should do here is write the main() method declaration on the whiteboard: public static void main(String[] args) Next, describe what each of public, static, void, main, String[], and args does. It is probably sufficient to just verbalize what each means. But if you want to write each word down as you verbalize, it helps to get the point across. a) public means that the method is visible everywhere b) static means you don't need an instance of the class to call the method c) void means the method doesn't return anything d) main is just the predefined method name for how to start a Java program e) String[] means the method accepts an array of strings as arguments to the method f) args is the name of the parameter to the method. Any name will do here. There is no hard and fast requirement that the parameter be called args. Sample Introductory Java Question 2 Given a line of text, verify that the beginning and ending parenthesis match up. How to Answer This is a little more complicated than the first, but still a coding problem a junior person should be able to code. The easiest way to do this is to push each beginning paran onto a stack, then when you get to a closing paran, pop an item off the stack. If the parens match ('(' and ')' or '{' and '}') continue. If not, there is a mismatch. If the pop is ever empty or the stack isn't empty at the end, there is a mismatch. Here is one solution that relies on the java.util.Stack class. import java.util.Stack; public class Match { public static boolean doParensMatch(String str) { Stack stack = new Stack<>(); char c; for (int i=0; i < str.length(); i++) { c = str.charAt(i); if (c == '(' || c == '{') { stack.push(c); } else if (c == '}') { if (stack.empty()) { return false; } else if (stack.peek() == '{') { stack.pop(); } } else if (c == ')') { if (stack.empty()) { return false; } else if (stack.peek() == '(') { stack.pop(); } else { return false; } } } return stack.empty(); } public static void main(String[] args) { System.out.println(doParensMatch("")); System.out.println(doParensMatch("()")); System.out.println(doParensMatch("{}")); System.out.println(doParensMatch("{()}")); System.out.println(doParensMatch("{123}")); System.out.println(doParensMatch("{)")); // failure System.out.println(doParensMatch("{((((((((()")); // failure } } Three things worth pointing out here: 1. Recursion isn't the answer to everything. 2. The main() method declaration here demonstrates lots of test cases. Don't just code a solution. Walk through the solution with at least one if not more test cases. 3. The Stack<Character> stack = new Stack<>(); line requires special mention. First, the <Character> bit demonstrates at least some knowledge of generics. Secondly, the <> declaration shows you've kept up with the language updates and know you don't have to do <Character> again. Little things like that are things that interviewers are looking for. You won't automatically fail with a line like Stack stack = new Stack() and casting when you get a character off the stack, but the more up to date you are with your code, the better you'll look. Advanced Java Interview Questions java interview questions As you get more experienced, you can expect more advanced types of coding problems. Not only will you be expected to code the solution, but you'll be expected to explain your answer more eloquently. Even more important with advanced Java programming questions is talking your way through the possible solution before coding. Returning to that email regex expression mentioned earlier, here's a simple solution that isn't fully RFC822 compliant but would probably suffice for the purposes of an interview. Pattern regexPattern = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE); Matcher matcher = regexPattern.matcher(emailStr); boolean found = matcher.find(); Can you come up with something comparable? If given that solution, could you explain what the different elements of the pattern do? What do the ^, $, +, and {2,6} indicate? (start of line/string, end of line/string, at least once, and at least 2 but not more than 6 times, respectively). Given the recent addition of new top level domains, that 6 is now too short. Good thing to point out if given that code as a possible solution. The CASE_INSENSITIVE isn't an absolute requirement, but does simplify the solution a little. Also, if asked to write the pattern, the compile(), matcher(), and find() calls aren't required either, but help to demonstrate your knowledge of the API to actually use the regular expression. On the more advanced side, you should expect pattern-related questions. These would range from describe the Singleton design pattern and how you would use it, to where in Java is the Singleton design pattern used, to code the Singleton design pattern, and finally what issues serialization can bring up with the Singleton design pattern. Observer, Factory, Decorator patterns are some others to be aware of that are found in Java. The best way to prepare for the more advanced interview questions for a particular company is to actually use Google to lookup what other people are reporting they were asked. This works great for larger companies. For instance, with a company like Google itself, you might run across a resource they provide: https://sites.google.com/site/coachingsessions1/interview-resources. When asked more advanced questions, the solution doesn't stop when the question is answered. You need to expect follow-up questions, like why did you do the operation in a particular way, what is the performance of your solution, and how can you improve it. For some reason, many of the more advanced questions are game related. Don't be surprised if you have to code the implementation of some game, or a part thereof. Some questions I've been asked include finding words on a Boggle board, reporting which if any player won from a Tic-Tac-Toe board, and dealing several card game related questions. More Java Interview Tips/Advice java interview questions answers As with any job interview, the technical questions are only part of the fun. You will also be asked fit and resume questions to determine if you're a good match for the company and dig deeper into your job experience. Do your best to learn something about the company and position beforehand. They shouldn't be the only people asking questions in the interview. It may seem obvious, but make sure you'll be a good fit with them, too. Are you more of a blue jeans and t-shirt person? While that might be more casual than most environments, you won't do well with a company wearing suits and ties every day. Do you prefer to sit in your cube coding with your headphones on? You won't do well with a company that requires lots of interacting with customers. If you don't ask, you'll never know. Be prepared to ask at least some questions of the interviewer. Try not to rely on the obvious questions like how long they've been at the company and don't go with a presumptuous question like, "When can I start?" It's okay to ask the same question of all interviewers if you think you'll get a different answer from each. A better question here might be "What is a typical workday like?" A bad question here is "How does your company/team do testing?" The former is good to see how each person does their job. There should be some similarities in the answers, but don't expect them to be 100% the same. The latter is still a good question, but not one to ask to each interviewer. At most two, to see if they report the same thing. A final thing to mention that might seem obvious, but is rarely if ever brought up during the interview: If an interviewer asks you to do the same coding problem that you addressed with an earlier interviewer, tell them. While you might feel great that you already know the answer and can do it right (or better) the second time around, the interviewers do talk to each other and will mark you down if you don't let them know about the duplicity of questions. They should know better but it sometimes happens. You don't want to be rejected because you didn't open your mouth about it.

- How to write accessors (getters) and mutators (setters) for fields in a class.

Book.java: Getters and Setters (a.k.a. Accessors and Mutators) Getters (a.k.a. Accessors) Getters, or accessors, are methods that provide access to an object's instance variables. In essence, we are providing a layer of indirection. Simple classes often have getters that return the associated instance variable and nothing more. For example: public String getTitle() { return title; } public String getAuthor() { return author; } public int getRating() { return rating; } simply return the title, author, and rating instance variables, respectively. Note that the name of the first getter is getTitle. Prefixing the corresponding instance variable with "get" is a common naming convention for getters. Getter methods shine in complex classes. For example, an object may need to perform network or database I/O to access the requested value. As such, having a getter method abstracts away the details of retrieving the desired value. Questions Why do we need getters? Why are getters useful abstractions? Setters (a.k.a. Mutators) Setters, or mutators, are methods that provider the caller with an opportunity to update the value of a particular instance variable. Similar to getters, setters are often named by prefixing the corresponding instance variable with "set". For example: public void setTitle(String title) { this.title = title; } public void setAuthor(String author) { this.author = author; } public void setRating(int rating) { this.rating = rating; } Note that, unlikely getters, setters have no return value. A setter's job is usually limited to changing the value of an instance variable. Like getters, setters provide a useful layer of indirection to manipulating instance variables. Suppose we want our Book class to only using rating values between 0 and 5. The setter provides an excellent opportunity for enforcing these constraints: public void setRating(int rating) { if (rating > 5) { this.rating = 5; } else if (rating < 0) { this.rating = 0; } else { this.rating = rating; } } This improved setRating setter can also be used by Book's constructor to ensure that we only initialize objects with valid ratings: public Book(String title, String author, int rating) { this.title = title; this.author = author; setRating(rating); }

how to call instance methods

// calling an instance method in the class 'Foo'. Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class. public static void geek(String name) { // code to be executed.... }

What instance fields and methods are.

Java fields are variables within Java classes. A Java method is a set of instructions that perform a task. A method can accept values, called parameters, and it can return these values back to the code that called the method. Both methods and fields have a type, the type of data they contain (such as an int or double).

Write a program that declares a String variable named name, an int variable named age, and a double variable named annualPay. Prompt the user for their name, age, and annualPay, and store these values in the corresponding variables. Then display a message containing this information. A sample run of your program for the values indicated below should look exactly like this: Please enter your name: Ada Lovelace Please enter your age: 27 Please enter your annual pay: 243.67 Your name is Ada Lovelace, your name contains 11 characters, your age is 27, and your annual pay is $243.67.

Skip to content Why GitHub? Enterprise Explore Marketplace Pricing Search Sign in Sign up 1 0 0 3588/au-cs260 Code Issues 0 Pull requests 0 Projects 0 Insights Join GitHub today GitHub is home to over 31 million developers working together to host and review code, manage projects, and build software together. au-cs260/HW/1/p2.java Junjun Huang update win 92eb631 on Dec 6, 2014 26 lines (26 sloc) 835 Bytes //junjun huang assignment 1 package hw1; public class p2 { //Problem 2 //Write a program that declares the following: //1. a String variable named name //2. an int variable named age //3. a double variable named annualPay //Store your age, name, and desired annual income as literals in these variables. The program should display //these values on the screen in a manner similar to the following: //My name is Paul Cao, my age is 35 and I hope to earn $100.0 per year. public static void main(String [] args) { String name = "Junjun Huang"; int age = 28; double annualPay = 99.99; System.out.print("My name is "); System.out.print(name); System.out.print(", my age is "); System.out.print(age); System.out.print(" and I hope to earn $"); System.out.print(annualPay); System.out.print(" per year."); } } © 2019 GitHub, Inc. Terms Privacy Security Status Help Contact GitHub Pricing API Training Blog About

Write a program that prompts the user to enter an integer, and displays the String "Odd" to the screen if the integer is odd, and displays the String "Even" to the screen if the integer is even.

Stack Overflow Search... Log In Sign Up By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Home PUBLIC Stack Overflow Tags Users Jobs Teams Q&A for work Learn More An application that determines an entered integer to be odd or even in Java Ask Question 2 I'm new to the java language and have just learned basic stuff as of yet. I have to write an application that asks a user to enter an integer, and then display a statement that indicates whether an integer is even or odd. This is what I have done: import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); double divisibleByTwo = num % 2; if(divisibleByTwo == 0) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } } The above code works fine, but the software that grades my code requires my code to be in this format: import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd } public static boolean isEven(int number) { // check if number is even } } The following is my setup, but I have several mistakes in it, and am not really sure how to get going and have it work right. Any help would be appreciated. import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); isEven(num); boolean divisible; isDivisibleByTwo = divisible; if(divisible == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { // check if number is even int remainderByTwo = number % 2; boolean isDivisbleByTwo = (remainderByTwo == 0); return isDivisibleByTwo; } } java shareimprove this question asked Nov 21 '17 at 17:13 user8981016 196 1 What are your mistakes? Are you getting any errors? If so, what is the first one? And what line causes it? - Code-Apprentice Nov 21 '17 at 17:15 1 Possible duplicate of How to use return value from method in Java? - BackSlash Nov 21 '17 at 17:15 I suggest that you learn about local variables and return values. These seem to be the two critical concepts that you need to understand here. - Code-Apprentice Nov 21 '17 at 17:16 @Code-Apprentice: I was having a problem with the line isEven(num); -- as RAZ_Muh_Taz pointed out, it was a problem with not assigning values properly. RAZ_Muh_Taz's answer had me figure it out. - user8981016 Nov 22 '17 at 5:40 add a comment 3 Answers active oldest votes 3 In your first example you are assigning the variable correctly when you do double divisibleByTwo = num % 2; and then using that value that was returned you check if(divisibleByTwo == 0)... which returns true or false. However in the next sample of code you do isEven(num); //NO asignment!!!! boolean divisible; //defaults to false isDivisibleByTwo = divisible; if(divisible == true) //divisble will always be false Since you never assign divisible to the value returned by isEven your if statement will always return false because the default value of boolean variables are false. You need to assign the value returned by your isEven method call and then use that value like this boolean isDivisibleByTwo = isEven(num); if(isDivisibleByTwo) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); Or you can use the returned value of the isEven method without having to assign it to a variable like this if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); shareimprove this answer edited Nov 21 '17 at 17:26 answered Nov 21 '17 at 17:17 RAZ_Muh_Taz 3,6171822 add a comment 1 You don't need to overcomplicate things. You just need cleaner and simple code: public class OddEven { public static void main(String[] args) { // accept user input and check if number is even or odd Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); boolean remainder = isEven(num); if (remainder == true) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } public static boolean isEven(int number) { if (number % 2 == 0) return true; else return false; } } shareimprove this answer answered Nov 21 '17 at 17:26 Saurabh 427518 add a comment 0 Your goal is to do all the calculation in the isEven method, your main method will only be used to get the number from the user and call the other method. No need to do calculations there. In other words something like the following : import java.util.Scanner; class EvenOdd { public static void main(String[] args) { // Get the user input Scanner input = new Scanner(System.in); System.out.print("Enter an integer >> "); int num = input.nextInt(); // Check if the input is correct ? // Call your method and check the return value if(isEven(num)) System.out.println("The integer entered is even."); else System.out.println("The integer entered is odd."); } // And then your method is good public static boolean isEven(int number) { // check if number is even return (number % 2) == 0; } } shareimprove this answer answered Nov 21 '17 at 17:20 Joachim Huet 35719 add a comment Your Answer Sign up or log in Sign up using Google Sign up using Facebook Sign up using Email and Password Post as a guest Name Email Required, but never shown Post Your Answer By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies. Not the answer you're looking for? Browse other questions tagged java or ask your own question. asked 1 year, 3 months ago viewed 502 times active 1 year, 3 months ago The Buffalo Group The Buffalo Group Government JAVA Software Developer (TOP SECRET clearance and above required) Reston, VA$80k - $180kPaid relocation java javascript TS/SCI DevOps Automation Engineer Reston, VA$100k - $150kPaid relocation amazon-web-services jenkins View all 2 job openings! Adaptive Financial Consulting Adaptive Financial Consulting New York, NY We have great benefits! Travel between offices Highly competitive salary Coffee, snacks and fruit treats at the office Internal tech meetups (with lunch provided) + 6 more benefits Learn more Linked -1 How to use return value from method in Java? Related 1321 Fastest way to determine if an integer's square root is an integer 3127 How do I generate random integers within a specific range in Java? 87 Are static variables shared between threads? 17 java static initialization with inheritance -1 Java Programming Error: Actual and formal argument lists differ in length -3 I want this code to separate even and odd numbers 1 sum of integers. add them. check if sum is odd or even. print the sum of digits and also print if odd or even -4 why the exception is thrown when it should not -9 I/P-a string S.O/P: For each digit start from 0-9,print count of their occurrence in S.Print10 lines,each line contain 2 space separated integers -4 Would it make any difference giving arguments using scanner class instead of command line arguments? Hot Network Questions Why is mind meld hard for T'pol in Star Trek: Enterprise? Can a hotel cancel a confirmed reservation? Math Saturation Symbol How would an AI self awareness kill switch work? How much mayhem could I cause as a sentient fish? Dilemma of explaining to interviewer that he is the reason for declining second interview How can my powered armor quickly replace its ceramic plates? Could a phylactery of a lich be a mirror or does it have to be a box? Can an insurance company drop you after receiving a bill and refusing to pay? How can I get my players to come to the game session after agreeing to a date? Making him into a bully (how to show mild violence) Citing paywalled articles accessed via illegal web sharing How to say "Brexit" in Latin? How to limit sight distance to 1 KM Why avoid shared user accounts? Publishing research using outdated methods Traveling through the asteriod belt? Why did other German political parties disband so fast when Hitler was appointed chancellor? Why do neural networks need so many training examples to perform? Finding a mistake using Mayer-Vietoris Why zero tolerance on nudity in space? How did Ancient Greek 'πυρ' become English 'fire?' A starship is travelling at 0.9c and collides with a small rock. Will it leave a clean hole through, or will more happen? How should I handle players who ignore the session zero agreement? question feed STACK OVERFLOW Questions Jobs Developer Jobs Directory Salary Calculator Help Mobile Disable Responsiveness PRODUCTS Teams Talent Engagement Enterprise COMPANY About Press Work Here Legal Privacy Policy Contact Us STACK EXCHANGE NETWORK Technology Life / Arts Culture / Recreation Science Other Blog Facebook Twitter LinkedIn site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0 with attribution required. rev 2019.2.28.32962

How to declare a variable

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false). int score;

How to assign a value to a variable.

Java is pass-by-value. That means pass-by-copy Declare an int variable and assign it the value '7'. The bit pattern for 7 goes into the variable named x. int x = 7;

How to write a constructor.

When the object is created, Java calls the constructor first. Any code you have in your constructor will then get executed. You don't need to make any special calls to a constructor method - they happen automatically when you create a new object. Constructor methods take the same name as the class.

How to read keyboard input from the user.

Input from Keyboard The input Function Input via keyboard There are hardly any programs without any input. Input can come in various ways, for example from a database, another computer, mouse clicks and movements or from the internet. Yet, in most cases the input stems from the keyboard. For this purpose, Python provides the function input(). input has an optional parameter, which is the prompt string. If the input function is called, the program flow will be stopped until the user has given an input and has ended the input with the return key. The text of the optional parameter, i.e. the prompt, will be printed on the screen. The input of the user will be interpreted. If the user e.g. puts in an integer value, the input function returns this integer value. If the user on the other hand inputs a list, the function will return a list. Let's have a look at the following example: name = input("What's your name? ") print("Nice to meet you " + name + "!") age = input("Your age? ") print("So, you are already " + str(age) + " years old, " + name + "!") We save the program as "input_test.py" and run it: $ python input_test.py What's your name? "Frank" Nice to meet you Frank! Your age? 30 So, you are already 30 years old, Frank! It is quite possible that you may have forgotten to include your name into quotes. If so, there is also a good chance that you may have been confused with the error message: Traceback (most recent call last): File "input_test.py", line 1, in <module> name = input("What's your name? ") File "<string>", line 1, in <module> NameError: name 'Frank' is not defined We mentioned it at the beginning of this chapter on the input function: input interprets the input. That's the reason, why we had to cast the variable "age" into a string. If you don't wrap your name into quotes, Python takes your name as a variable. So, the error message makes sense! Let's have a look at further examples. We will use the function type to check the type of the variables: >>> name = input("What's your name? ") What's your name? "John" >>> >>> age = input("Your age? ") Your age? 38 >>> print(age, type(age)) (38, <type 'int'>) >>> colours = input("Your favourite colours? ") Your favourite colours? ["red","green","blue"] >>> print(colours) ['red', 'green', 'blue'] >>> print(colours, type(colours)) (['red', 'green', 'blue'], <type 'list'>) >>> Input with raw_input() raw_input does not interpret the input. It always returns the input of the user without changes, i.e. raw. This raw input can be changed into the data type needed for the algorithm. To accomplish this we can use either a casting function or the eval function. Once more, we use the interactive shell to demonstrate this behaviour: >>> age = raw_input("Your age? ") Your age? 38 >>> print(age, type(age)) ('38', <type 'str'>) >>> >>> age = int(raw_input("Your age? ")) Your age? 42 >>> print(age, type(age)) (42, <type 'int'>) >>> >>> programming_language = raw_input("Your favourite programming languages? ") Your favourite programming languages? ["Python", "Lisp","C++"] >>> print(programming_language, type(programming_language)) ('["Python", "Lisp","C++"]', <type 'str'>) >>> >>> programming_language = eval(raw_input("Your favourite programming languages? ")) Your favourite programming languages? ["Python", "Lisp","C++"] >>> print(programming_language, type(programming_language)) (['Python', 'Lisp', 'C++'], <type 'list'>) >>> Using the casting function list in the last example, doesn't return, what some readers might expect: >>> programming_language = list(raw_input("Your favourite programming languages? ")) Your favourite programming languages? ["Python", "Lisp","C++"] >>> print(programming_language, type(programming_language)) ([' ', '[', '"', 'P', 'y', 't', 'h', 'o', 'n', '"', ',', ' ', '"', 'L', 'i', 's', 'p', '"', ',', '"', 'C', '+', '+', '"', ']'], <type 'list'>) >>>

What the keyword return does and when to use it,

The return keyword is used to return from a method when its execution is complete. When a return statement is reached in a method, the program returns to the code that invoked it. A method can return a value or reference type or does not return a value.

What a reference variable is

A reference variable is an alias, that is, another name for an already existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

Understand the dangling else problem.

Dangling else. The dangling else is a problem in computer programming in which an optional else clause in an if-then(-else) statement results in nested conditionals being ambiguous. Formally, the reference context-free grammar of the language is ambiguous, meaning there is more than one correct parse tree.

Understand the difference between == and equals.

In general both equals() and "==" operator in Java are used to compare objects to check equality but here are some of the differences between the two: ... In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.

How to display output to the screen

Print output in Java Java Output. You can simply use System.out.println() , System.out.print() or System.out.printf() to send output to standard output (screen). System is a class and out is a public static field which accepts output data.

How to solve a problem algorithmically (and know what that means!)

Problems, Solutions, and Tools I have a problem! I need to thank Aunt Kay for the birthday present she sent me. I could send a thank you note through the mail. I could call her on the telephone. I could send her an email message. I could drive to her house and thank her in person. In fact, there are many ways I could thank her, but that's not the point. The point is that I must decide how I want to solve the problem, and use the appropriate tool to implement (carry out) my plan. The postal service, the telephone, the internet, and my automobile are tools that I can use, but none of these actually solves my problem. In a similar way, a computer does not solve problems, it's just a tool that I can use to implement my plan for solving the problem. Knowing that Aunt Kay appreciates creative and unusual things, I have decided to hire a singing messenger to deliver my thanks. In this context, the messenger is a tool, but one that needs instructions from me. I have to tell the messenger where Aunt Kay lives, what time I would like the message to be delivered, and what lyrics I want sung. A computer program is similar to my instructions to the messenger. The story of Aunt Kay uses a familiar context to set the stage for a useful point of view concerning computers and computer programs. The following list summarizes the key aspects of this point of view. A computer is a tool that can be used to implement a plan for solving a problem. A computer program is a set of instructions for a computer. These instructions describe the steps that the computer must follow to implement a plan. An algorithm is a plan for solving a problem. A person must design an algorithm. A person must translate an algorithm into a computer program. This point of view sets the stage for a process that we will use to develop solutions to Jeroo problems. The basic process is important because it can be used to solve a wide variety of problems, including ones where the solution will be written in some other programming language. An Algorithm Development Process Every problem solution starts with a plan. That plan is called an algorithm. An algorithm is a plan for solving a problem. There are many ways to write an algorithm. Some are very informal, some are quite formal and mathematical in nature, and some are quite graphical. The instructions for connecting a DVD player to a television are an algorithm. A mathematical formula such as πR2 is a special case of an algorithm. The form is not particularly important as long as it provides a good way to describe and check the logic of the plan. The development of an algorithm (a plan) is a key step in solving a problem. Once we have an algorithm, we can translate it into a computer program in some programming language. Our algorithm development process consists of five major steps. Step 1: Obtain a description of the problem. Step 2: Analyze the problem. Step 3: Develop a high-level algorithm. Step 4: Refine the algorithm by adding more detail. Step 5: Review the algorithm. Step 1: Obtain a description of the problem. This step is much more difficult than it appears. In the following discussion, the word client refers to someone who wants to find a solution to a problem, and the word developer refers to someone who finds a way to solve the problem. The developer must create an algorithm that will solve the client's problem. The client is responsible for creating a description of the problem, but this is often the weakest part of the process. It's quite common for a problem description to suffer from one or more of the following types of defects: (1) the description relies on unstated assumptions, (2) the description is ambiguous, (3) the description is incomplete, or (4) the description has internal contradictions. These defects are seldom due to carelessness by the client. Instead, they are due to the fact that natural languages (English, French, Korean, etc.) are rather imprecise. Part of the developer's responsibility is to identify defects in the description of a problem, and to work with the client to remedy those defects. Step 2: Analyze the problem. The purpose of this step is to determine both the starting and ending points for solving the problem. This process is analogous to a mathematician determining what is given and what must be proven. A good problem description makes it easier to perform this step. When determining the starting point, we should start by seeking answers to the following questions: What data are available? Where is that data? What formulas pertain to the problem? What rules exist for working with the data? What relationships exist among the data values? When determining the ending point, we need to describe the characteristics of a solution. In other words, how will we know when we're done? Asking the following questions often helps to determine the ending point. What new facts will we have? What items will have changed? What changes will have been made to those items? What things will no longer exist? Step 3: Develop a high-level algorithm. An algorithm is a plan for solving a problem, but plans come in several levels of detail. It's usually better to start with a high-level algorithm that includes the major part of a solution, but leaves the details until later. We can use an everyday example to demonstrate a high-level algorithm. Problem: I need a send a birthday card to my brother, Mark. Analysis: I don't have a card. I prefer to buy a card rather than make one myself. High-level algorithm: Go to a store that sells greeting cards Select a card Purchase a card Mail the card This algorithm is satisfactory for daily use, but it lacks details that would have to be added were a computer to carry out the solution. These details include answers to questions such as the following. "Which store will I visit?" "How will I get there: walk, drive, ride my bicycle, take the bus?" "What kind of card does Mark like: humorous, sentimental, risqué?" These kinds of details are considered in the next step of our process. Step 4: Refine the algorithm by adding more detail. A high-level algorithm shows the major steps that need to be followed to solve a problem. Now we need to add details to these steps, but how much detail should we add? Unfortunately, the answer to this question depends on the situation. We have to consider who (or what) is going to implement the algorithm and how much that person (or thing) already knows how to do. If someone is going to purchase Mark's birthday card on my behalf, my instructions have to be adapted to whether or not that person is familiar with the stores in the community and how well the purchaser known my brother's taste in greeting cards. When our goal is to develop algorithms that will lead to computer programs, we need to consider the capabilities of the computer and provide enough detail so that someone else could use our algorithm to write a computer program that follows the steps in our algorithm. As with the birthday card problem, we need to adjust the level of detail to match the ability of the programmer. When in doubt, or when you are learning, it is better to have too much detail than to have too little. Most of our examples will move from a high-level to a detailed algorithm in a single step, but this is not always reasonable. For larger, more complex problems, it is common to go through this process several times, developing intermediate level algorithms as we go. Each time, we add more detail to the previous algorithm, stopping when we see no benefit to further refinement. This technique of gradually working from a high-level to a detailed algorithm is often called stepwise refinement. Stepwise refinement is a process for developing a detailed algorithm by gradually adding detail to a high-level algorithm. Step 5: Review the algorithm. The final step is to review the algorithm. What are we looking for? First, we need to work through the algorithm step by step to determine whether or not it will solve the original problem. Once we are satisfied that the algorithm does provide a solution to the problem, we start to look for other things. The following questions are typical of ones that should be asked whenever we review an algorithm. Asking these questions and seeking their answers is a good way to develop skills that can be applied to the next problem. Does this algorithm solve a very specific problem or does it solve a more general problem? If it solves a very specific problem, should it be generalized? For example, an algorithm that computes the area of a circle having radius 5.2 meters (formula π*5.22) solves a very specific problem, but an algorithm that computes the area of any circle (formula π*R2) solves a more general problem. Can this algorithm be simplified? One formula for computing the perimeter of a rectangle is: length + width + length + width A simpler formula would be: 2.0 * (length + width) Is this solution similar to the solution to another problem? How are they alike? How are they different? For example, consider the following two formulae: Rectangle area = length * width Triangle area = 0.5 * base * height Similarities: Each computes an area. Each multiplies two measurements. Differences: Different measurements are used. The triangle formula contains 0.5. Hypothesis: Perhaps every area formula involves multiplying two measurements. Example 4.1: Pick and Plant This section contains an extended example that demonstrates the algorithm development process. To complete the algorithm, we need to know that every Jeroo can hop forward, turn left and right, pick a flower from its current location, and plant a flower at its current location. Problem Statement (Step 1) A Jeroo starts at (0, 0) facing East with no flowers in its pouch. There is a flower at location (3, 0). Write a program that directs the Jeroo to pick the flower and plant it at location (3, 2). After planting the flower, the Jeroo should hop one space East and stop. There are no other nets, flowers, or Jeroos on the island. Start Finish The starting situation for example 4.1 The finishing situation for example 4.1 Analysis of the Problem (Step 2) The flower is exactly three spaces ahead of the jeroo. The flower is to be planted exactly two spaces South of its current location. The Jeroo is to finish facing East one space East of the planted flower. There are no nets to worry about. High-level Algorithm (Step 3) Let's name the Jeroo Bobby. Bobby should do the following: Get the flower Put the flower Hop East Detailed Algorithm (Step 4) Let's name the Jeroo Bobby. Bobby should do the following: Get the flower Hop 3 times Pick the flower Put the flower Turn right Hop 2 times Plant a flower Hop East Turn left Hop once Review the Algorithm (Step 5) The high-level algorithm partitioned the problem into three rather easy subproblems. This seems like a good technique. This algorithm solves a very specific problem because the Jeroo and the flower are in very specific locations. This algorithm is actually a solution to a slightly more general problem in which the Jeroo starts anywhere, and the flower is 3 spaces directly ahead of the Jeroo. Java Code for "Pick and Plant" A good programmer doesn't write a program all at once. Instead, the programmer will write and test the program in a series of builds. Each build adds to the previous one. The high-level algorithm will guide us in this process. A good programmer works incrementally, add small pieces one at a time and constantly re-checking the work so far. FIRST BUILD To see this solution in action, create a new Greenfoot4Sofia scenario and use the Edit Palettes Jeroo menu command to make the Jeroo classes visible. Right-click on the Island class and create a new subclass with the name of your choice. This subclass will hold your new code. The recommended first build contains three things: The main method (here myProgram() in your island subclass). Declaration and instantiation of every Jeroo that will be used. The high-level algorithm in the form of comments. 1 2 3 4 5 6 7 8 9 10 11 12 public void myProgram() { Jeroo bobby = new Jeroo(); this.add(bobby); // --- Get the flower --- // --- Put the flower --- // --- Hop East --- } // ===== end of method myProgram() ===== The instantiation at the beginning of myProgram() places bobby at (0, 0), facing East, with no flowers. Once the first build is working correctly, we can proceed to the others. In this case, each build will correspond to one step in the high-level algorithm. It may seem like a lot of work to use four builds for such a simple program, but doing so helps establish habits that will become invaluable as the programs become more complex. SECOND BUILD This build adds the logic to "get the flower", which in the detailed algorithm (step 4 above) consists of hopping 3 times and then picking the flower. The new code is indicated by comments that wouldn't appear in the original (they are just here to call attention to the additions). The blank lines help show the organization of the logic. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 public void myProgram() { Jeroo bobby = new Jeroo(); this.add(bobby); // --- Get the flower --- bobby.hop(3); // <-- new code to hop 3 times bobby.pick(); // <-- new code to pick the flower // --- Put the flower --- // --- Hop East --- } // ===== end of method myProgram() ===== By taking a moment to run the work so far, you can confirm whether or not this step in the planned algorithm works as expected. THIRD BUILD This build adds the logic to "put the flower". New code is indicated by the comments that are provided here to mark the additions. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public void myProgram() { Jeroo bobby = new Jeroo(); this.add(bobby); // --- Get the flower --- bobby.hop(3); bobby.pick(); // --- Put the flower --- bobby.turn(RIGHT); // <-- new code to turn right bobby.hop(2); // <-- new code to hop 2 times bobby.plant(); // <-- new code to plant a flower // --- Hop East --- } // ===== end of method myProgram() ===== FOURTH BUILD (final) This build adds the logic to "hop East". 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public void myProgram() { Jeroo bobby = new Jeroo(); this.add(bobby); // --- Get the flower --- bobby.hop(3); bobby.pick(); // --- Put the flower --- bobby.turn(RIGHT); bobby.hop(2); bobby.plant(); // --- Hop East --- bobby.turn(LEFT); // <-- new code to turn left bobby.hop(); // <-- new code to hop 1 time } // ===== end of method myProgram() ===== Example 4.2: Replace Net with Flower This section contains a second example that demonstrates the algorithm development process. Problem Statement (Step 1) There are two Jeroos. One Jeroo starts at (0, 0) facing North with one flower in its pouch. The second starts at (0, 2) facing East with one flower in its pouch. There is a net at location (3, 2). Write a program that directs the first Jeroo to give its flower to the second one. After receiving the flower, the second Jeroo must disable the net, and plant a flower in its place. After planting the flower, the Jeroo must turn and face South. There are no other nets, flowers, or Jeroos on the island. Start Finish The starting situation for example 4.2 The finishing situation for example 4.2 Analysis of the Problem (Step 2) Jeroo_2 is exactly two spaces behind Jeroo_1. The only net is exactly three spaces ahead of Jeroo_2. Each Jeroo has exactly one flower. Jeroo_2 will have two flowers after receiving one from Jeroo_1. One flower must be used to disable the net. The other flower must be planted at the location of the net, i.e. (3, 2). Jeroo_1 will finish at (0, 1) facing South. Jeroo_2 is to finish at (3, 2) facing South. Each Jeroo will finish with 0 flowers in its pouch. One flower was used to disable the net, and the other was planted. High-level Algorithm (Step 3) Let's name the first Jeroo Ann and the second one Andy. Ann should do the following: Find Andy (but don't collide with him) Give a flower to Andy (he will be straight ahead) After receiving the flower, Andy should do the following: Find the net (but don't hop onto it) Disable the net Plant a flower at the location of the net Face South Detailed Algorithm (Step 4) Let's name the first Jeroo Ann and the second one Andy. Ann should do the following: Find Andy Turn around (either left or right twice) Hop (to location (0, 1)) Give a flower to Andy Give ahead Now Andy should do the following: Find the net Hop twice (to location (2, 2)) Disable the net Toss Plant a flower at the location of the net Hop (to location (3, 2)) Plant a flower Face South Turn right Review the Algorithm (Step 5) The high-level algorithm helps manage the details. This algorithm solves a very specific problem, but the specific locations are not important. The only thing that is important is the starting location of the Jeroos relative to one another and the location of the net relative to the second Jeroo's location and direction. Java Code for "Replace Net with Flower" As before, the code should be written incrementally as a series of builds. Four builds will be suitable for this problem. As usual, the first build will contain the main method, the declaration and instantiation of the Jeroo objects, and the high-level algorithm in the form of comments. The second build will have Ann give her flower to Andy. The third build will have Andy locate and disable the net. In the final build, Andy will place the flower and turn East. FIRST BUILD This build creates the main method, instantiates the Jeroos, and outlines the high-level algorithm. In this example, the main method would be myProgram() contained within a subclass of Island. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public void myProgram() { Jeroo ann = new Jeroo(0, 0, NORTH, 1); this.add(ann); Jeroo andy = new Jeroo(0, 2 , 1); // default EAST this.add(andy); // --- Ann, find Andy --- // --- Ann, give Andy a flower --- // --- Andy, find and disable the net --- // --- Andy, place a flower at (3, 2) --- // --- Andy, face South --- } // ===== end of method myProgram() ===== SECOND BUILD This build adds the logic for Ann to locate Andy and give him a flower. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public void myProgram() { Jeroo ann = new Jeroo(0, 0, NORTH, 1); this.add(ann); Jeroo andy = new Jeroo(0, 2 , 1); // default EAST this.add(andy); // --- Ann, find Andy --- ann.turn(LEFT); ann.turn(LEFT); ann.hop(); // Now, Ann is at (0, 1) facing South, and Andy is directly ahead // --- Ann, give Andy a flower --- ann.give(AHEAD); // Ann now has 0 flowers, Andy has 2 // --- Andy, find and disable the net --- // --- Andy, place a flower at (3, 2) --- // --- Andy, face South --- } // ===== end of method myProgram() ===== THIRD BUILD This build adds the logic for Andy to locate and disable the net. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public void myProgram() { Jeroo ann = new Jeroo(0, 0, NORTH, 1); this.add(ann); Jeroo andy = new Jeroo(0, 2 , 1); // default EAST this.add(andy); // --- Ann, find Andy --- ann.turn(LEFT); ann.turn(LEFT); ann.hop(); // Now, Ann is at (0, 1) facing South, and Andy is directly ahead // --- Ann, give Andy a flower --- ann.give(AHEAD); // Ann now has 0 flowers, Andy has 2 // --- Andy, find and disable the net --- andy.hop(2); // Andy is at (2, 2) facing the net andy.toss(); // --- Andy, place a flower at (3, 2) --- // --- Andy, face South --- } // ===== end of method myProgram() ===== FOURTH BUILD (final) This build adds the logic for Andy to place a flower at (3, 2) and turn South. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 public void myProgram() { Jeroo ann = new Jeroo(0, 0, NORTH, 1); this.add(ann); Jeroo andy = new Jeroo(0, 2 , 1); // default EAST this.add(andy); // --- Ann, find Andy --- ann.turn(LEFT); ann.turn(LEFT); ann.hop(); // Now, Ann is at (0, 1) facing South, and Andy is directly ahead // --- Ann, give Andy a flower --- ann.give(AHEAD); // Ann now has 0 flowers, Andy has 2 // --- Andy, find and disable the net --- andy.hop(2); // Andy is at (2, 2) facing the net andy.toss(); // --- Andy, place a flower at (3, 2) --- andy.hop(); andy.plant(); // --- Andy, face South --- andy.turn(RIGHT); } // ===== end of method myProgram() =====

A publishing company sells textbooks for a 25 percent profit. If you know the retail price of a textbook, then you can calculate the profit made on it with the formula profit = retailPrice * 0.25 Write a Java program that stores the retail price of textbook costing $72.95 in a variable called retailPrice, calculates the amount of profit made on that textbook, and displays the result to the screen

...

How to declare a variable of type String.

Ask Question 2 This question already has an answer here: What are classes, references and objects? 9 answers class Demo { String title; private int num; } String is a class, so when we declare title, is that treated as object or just a variable? I know this is a very basic thing, but i need help. Thanks in advance.

Understand operator precedence and associativity

Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example '*' and '/' have same precedence and their associativity is Left to Right, so the expression "100 / 10 * 10" is treated as "(100 / 10) * 10".

What widening, narrowing, and casting are.

Widening Widening, also known as upcasting is a conversion that takes place in the following situations - Widening is taking place when a small primitive type value is automatically accommodated in a bigger/wider primitive data type. Widening is taking place when a reference variable of a subclass is automatically accommodated in the reference variable of its superclass. Widening a smaller primitive value to a bigger primitive type. class A { public static void main(String... ar) { byte b=10; short s= b; //byte value is widened to short int i=b; //byte value is widened to int long l=b; //byte value is widened to long float f=b; //byte value is widened to float double d=b; //byte value is widened to double System.out.println("short value : "+ s); System.out.println("int value : "+ i); System.out.println("long value : "+ l); System.out.println("float value : "+ f); System.out.println("double value : "+ d); } } Output- short value : 10 int value : 10 long value : 10 float value : 10.0 double value : 10.0 In the preceding code, we have widened a smaller byte value to several bigger primitive values like byte, short, int, long and float. Widening a subclass object reference to a wider superclass object reference. This is also known as upcasting the subclass reference to its superclass reference. class A { public void message() { System.out.println("message from A"); } } class B extends A { public void message() { System.out.println("message from B"); } public static void main(String... ar) { B b = new B(); A a = b; //reference of a subclass(B) type is widened to the reference of superclass(A) type. a.message(); } } Output- Message from B In the previous code, we have a class A extended by class B, hence A is a superclass and B is its subclass. Method message() of superclass A is overridden in subclass B. We have created an object of subclass B, which is assigend to its reference, b. This subclass B reference, b is widened/upcasted and assigned to superclass A reference, a. Narrowing Narrowing also known as downcasting/casting is a conversion that takes place in such situations - Narrowing a wider/bigger primitive type value to a smaller primitive type value. Narrowing the superclass reference to the reference of its subclass, during inheritance. Narrowing a bigger primitive value to a small primitive value. class A { public static void main(String... ar) { double d =10.5; byte b = (byte)d; //Narrowing double to byte short s= (short)d; //Narrowing double to short int i= (int)d; //Narrowing double to int long l= (long)d; //Narrowing double to long float f= (float)d; //Narrowing double to float System.out.println("Original double value : " +d); System.out.println("Narrowing double value to short : "+ s); System.out.println("Narrowing double value to int : "+ i); System.out.println("Narrowing double value to long : "+ l); System.out.println("Narrowing double value to float : "+ f); System.out.println("Narrowing double value to byte : "+ b); } } Output- Original double value : 10.5 Narrowing double value to short : 10 Narrowing double value to int : 10 Narrowing double value to long : 10 Narrowing double value to float : 10.5 Narrowing double value to byte : 10 In the preceding code, we have narrowed a bigger double value to several smaller primitive values like byte, short, int, long and float by putting a cast around the double value. Narrowing an superclass object reference to subclass object reference. This is also known as downcasting the superclass reference to its subclass reference. class A //superclass { public void message() { System.out.println("message from A"); } } class B extends A //subclass { public void message() { System.out.println("message from B"); } public static void main(String... ar) { A a = new B(); //object of subclass(B) is referenced by reference of superclass(A) B b = (B)a; //reference of a superclass(B) type is downcasted/narrowed to the reference of subclass(A) type. b.message(); } } Output - message from B In the last code, we have a class A extended by class B, hence A is superclass and B is its subclass. Method message() of superclass is overridden in subclass. We have created an object of subclass(B), which is assigend to the reference of superclass(A), a. This superclass(A) reference, a is narrowed/downcasted and assigned to subclass(B) reference, b.

- Understand the difference between = and ==

The Difference Between "is" and "==" in Python. Python has two operators for equality comparisons, "is" and "==" (equals). ... There's a difference in meaning between equal and identical. And this difference is important when you want to understand how Python's is and == comparison operators behave.

- How to create a named constant.

Name an array constant Click Formulas > Define Name. In the Name box, enter a name for your constant. In the Refers to box, enter your constant. ... Click OK. In your worksheet, select the cells that will contain your constant. In the formula bar, enter an equal sign and the name of the constant, such as =Quarter1. Press Ctrl+Shift+Enter.

- Understand operator precedence and associativity.

Associativity is used when two operators of same precedence appear in an expression. Associativity can be either Left to Right or Right to Left. For example '*' and '/' have same precedence and their associativity is Left to Right, so the expression "100 / 10 * 10" is treated as "(100 / 10) * 10".

How to declare a variable of class type.

Declaring Member Variables There are several kinds of variables: Member variables in a class—these are called fields. Variables in a method or block of code—these are called local variables. Variables in method declarations—these are called parameters. The Bicycle class uses the following lines of code to define its fields: public int cadence; public int gear; public int speed; Field declarations are composed of three components, in order: Zero or more modifiers, such as public or private. The field's type. The field's name. The fields of Bicycle are named cadence, gear, and speed and are all of data type integer (int). The public keyword identifies these fields as public members, accessible by any object that can access the class. Access Modifiers The first (left-most) modifier used lets you control what other classes have access to a member field. For the moment, consider only public and private. Other access modifiers will be discussed later. public modifier—the field is accessible from all classes. private modifier—the field is accessible only within its own class. In the spirit of encapsulation, it is common to make fields private. This means that they can only be directly accessed from the Bicycle class. We still need access to these values, however. This can be done indirectly by adding public methods that obtain the field values for us: public class Bicycle { private int cadence; private int gear; private int speed; public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; } public int getCadence() { return cadence; } public void setCadence(int newValue) { cadence = newValue; } public int getGear() { return gear; } public void setGear(int newValue) { gear = newValue; } public int getSpeed() { return speed; } public void applyBrake(int decrement) { speed -= decrement; } public void speedUp(int increment) { speed += increment; } } Types All variables must have a type. You can use primitive types such as int, float, boolean, etc. Or you can use reference types, such as strings, arrays, or objects. Variable Names All variables, whether they are fields, local variables, or parameters, follow the same naming rules and conventions that were covered in the Language Basics lesson, Variables—Naming. In this lesson, be aware that the same naming rules and conventions are used for method and class names, except that the first letter of a class name should be capitalized, and the first (or only) word in a method name should be a verb.

Know what the relational operators are and how to use them

Equality, Relational, and Conditional Operators The Equality and Relational Operators The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal. == equal to != not equal to > greater than >= greater than or equal to < less than <= less than or equal to The following program, ComparisonDemo, tests the comparison operators: class ComparisonDemo { public static void main(String[] args){ int value1 = 1; int value2 = 2; if(value1 == value2) System.out.println("value1 == value2"); if(value1 != value2) System.out.println("value1 != value2"); if(value1 > value2) System.out.println("value1 > value2"); if(value1 < value2) System.out.println("value1 < value2"); if(value1 <= value2) System.out.println("value1 <= value2"); } } Output: value1 != value2 value1 < value2 value1 <= value2 The Conditional Operators The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed. && Conditional-AND || Conditional-OR The following program, ConditionalDemo1, tests these operators: class ConditionalDemo1 { public static void main(String[] args){ int value1 = 1; int value2 = 2; if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2"); if((value1 == 1) || (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1"); } } Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result." The following program, ConditionalDemo2, tests the ?: operator: class ConditionalDemo2 { public static void main(String[] args){ int value1 = 1; int value2 = 2; int result; boolean someCondition = true; result = someCondition ? value1 : value2; System.out.println(result); } } Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments). The Type Comparison Operator instanceof The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface. class InstanceofDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent)); System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child)); System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface)); System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent)); System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child)); System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface)); } } class Parent {} class Child extends Parent implements MyInterface {} interface MyInterface {} Output: obj1 instanceof Parent: true obj1 instanceof Child: false obj1 instanceof MyInterface: false obj2 instanceof Parent: true obj2 instanceof Child: true obj2 instanceof MyInterface: true When using the instanceof operator, keep in mind that null is not an instance of anything.

Write a Java program that will display: • your name on the first line, • your street address on the second line, • your city, state, and zipcode on the third line, • your email address on the fourth line, and • your phone number on the fifth line. Place a comment with today's date at the top of the program. Test your program by entering it, compiling it, and running it in BlueJ. Make sure that your city and state are separated by a comma, as is common practice when writing addresses. Your phone number should similarly have dashes (or dots, if you prefer) separating the area code, the prefix, and the body, as is common practice when writing phone numbers.

Java Programming Exercies Java Exercises: Print hello and your name on a separate lines Java Basic: Exercise-1 with Solution Write a Java program to print 'Hello' on screen and then print your name on a separate line. Pictorial Presentation: Java: Print hello and your name on a separate lines Sample Solution: Java Code: public class Exercise1 { public static void main(String[] args) { System.out.println("Hello\nAlexandra Abramov!"); } } Copy Sample Output: Hello Alexandra Abramov! Flowchart: Flowchart: Print hello and your name on a separate lines Sample solution using input from the user: Java Code: import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner input = new Scanner (System.in); System.out.print("Input your first name: "); String fname = input.next(); System.out.print("Input your last name: "); String lname = input.next(); System.out.println(); System.out.println("Hello \n"+fname+" "+lname); } } Copy Sample Output: Input your first name: James Input your last name: Smith Hello James Smith Flowchart: Flowchart: Java exercises: Print hello and your name on a separate lines

How to write an if-else-if-statement.

Java if...else (if-then-else) Statement. The if statement executes a certain section of code if the test expression is evaluated to true. The if statement may have an optional else block. Statements inside the body of else statement are executed if the test expression is evaluated to false .

Design a TestScores class that has fields to hold three test scores. The class should have a constructor that accepts three integer test scores as arguments and assigns these arguments to the three test score fields. The class should also have accessor methods for the three test score fields, a method that returns the average of the test scores, and a method that returns the letter grade that is assigned for the test score average according to the following grading scheme: Test score average Letter grade 90% ≤ average A 80% ≤ average < 90% B 70% ≤ average < 80% C 60% ≤ average < 70% D average < 60% F

Level Up Lunch M≡NU TestScores class program Java / Exercises On this page The problem Breaking it down Output Level Up Related Hey friends, support level up lunch by signing up with project fi and receive a $20 credit!! The problem Design a TestScores class that has fields to hold three test scores. The class should have a constructor, accessor and mutator methods for the test score fields, and a method that returns the average of the test scores. Demonstrate the class by writing a separate program that creates an instance of the class. The program should ask the user to enter three test scores, which are stored in the TestScores object. Then the program should display the average of the scores, as reported by the TestScores object. Breaking it down TestScores Class public class TestScores { private double score1; private double score2; private double score3; public TestScores(double score1, double score2, double score3) { this.score1 = score1; this.score2 = score2; this.score3 = score3; } public void setScore1(double score) { score1 = score; } public void setScore2(double score) { score2 = score; } public void setScore3(double score) { score3 = score; } public double getScore1() { return score1; } public double getScore2() { return score2; } public double getScore3() { return score3; } public double getAverageScore() { return (score1 + score2 + score3) / 3; } } Main program public static void main(String[] args) { double test1; double test2; double test3; // Create a scanner for keyboard input. Scanner keyboard = new Scanner(System.in); System.out.print("Enter test score: "); test1 = keyboard.nextDouble(); System.out.print("Enter test score: "); test2 = keyboard.nextDouble(); System.out.print("Enter test score: "); test3 = keyboard.nextDouble(); // close scanner keyboard.close(); TestScoresClassProgram classProgram = new TestScoresClassProgram(); TestScores scores = classProgram.new TestScores(test1, test2, test3); // Display average System.out.println("The average test score: " + scores.getAverageScore()); } Output Enter test score: 10 Enter test score: 30 Enter test score: 25 The average test score: 21.666666666666668 Level Up Add a test score 4, 5, 6. Is this TestScores class flexible to continue to add scores? Modify the program to accept values and add scores to a list. Format the average test score to 2 decimal points. Convert the average test score to a grade scale using guava range map TestScores class program posted by Justin Musgrove on 05 July 2014 Tagged: java and java-exercises-beginner Share on: Twitter Facebook Google+ About us Blog Style Guide Exercises Examples Tutorials Twitter Facebook google+ GitHub YouTube This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Write a Circle class that has the following fields: • a double field called radius • a final double field called PI that is initialized to the value 3.14159. The class should also have the following methods: • a constructor that accepts the radius of the circle as an argument. • a setter for the radius field. • a getter for the radius field. • a getArea method that returns the area of the circle. • a getDiameter method that returns the diameter of the circle. • a getCircumference method that returns the circumference of the circle. Now write an application program that demonstrates the Circle class by asking the user for the circle's radius, creating a Circle object, and reporting the circle's area, diameter, and circumference.

The problem Write a Circle class that has the following fields: radius: a double PI: a final double initialized with the value 3.14159 The class should have the following methods: Constructor. accepts the radius of the circle as an argument. Constructor. A no-arg constructor that sets the radius field to 0.0. setRadius. A mutator method for the radius field. getRadius. An accessor method for the radius field. getArea. Returns the area of the circle which is calculated as * area=PIradiusradius getDiameter. Returns the diameter of the circle which is calculated as diameter=radius*2 getCircumference. Returns the circumference of the circle, which is calculated as circumference= 2PIradius Write a program that demonstrates the Circle class by asking the user for the circle's radius, creating a Circle object, and then reporting the circle's area, diameter, and circumference. Breaking it down Create circle class public class Circle { private final double PI = 3.14159; private double radius; public Circle() { radius = 0.0; } public Circle(double r) { radius = r; } public void setRadius(double r) { radius = r; } public double getRadius() { return radius; } public double getArea() { return PI * radius * radius; } public double getDiameter() { return radius * 2; } public double getCircumference() { return 2 * PI * radius; } } Create program public static void main(String[] args) { // Create a Scanner object for keyboard input. Scanner keyboard = new Scanner(System.in); // Ask user to input circle radius System.out.print("Enter the radius of a circle: "); double radius = keyboard.nextDouble(); // close keyboard keyboard.close(); // Create a Circle object passing in user input CircleClass circleClass = new CircleClass(); Circle circle = circleClass.new Circle(radius); // Display circle information System.out.println("Area is " + circle.getArea()); System.out.println("Diameter is " + circle.getDiameter()); System.out.println("Circumference is " + circle.getCircumference()); } Output Enter the radius of a circle: 10.5 Area is 346.3602975 Diameter is 21.0 Circumference is 65.97339 Unit tests @Test public void test_getArea() { CircleClass circleClass = new CircleClass(); Circle circle = circleClass.new Circle(10); assertEquals(314.159, circle.getArea(), 0); } @Test public void test_getDiameter() { CircleClass circleClass = new CircleClass(); Circle circle = circleClass.new Circle(10); assertEquals(20, circle.getDiameter(), 0); } @Test public void test_getCircumference() { CircleClass circleClass = new CircleClass(); Circle circle = circleClass.new Circle(10); assertEquals(62.8318, circle.getCircumference(), 0); }

How to call a constructor (in an application program) to create an instance of a class (and assign a variable of that class type to reference it).

Home > Articles > Programming > Java Introduction to Classes, Objects, Methods and Strings in Java SE8 Paul Deitel By Harvey Deitel and Paul Deitel Apr 9, 2014 📄 Contents ␡ 3.1 Introduction 3.2 Instance Variables, set Methods and get Methods 3.3 Primitive Types vs. Reference Types 3.4 Account Class: Initializing Objects with Constructors 3.5 Account Class with a Balance; Floating-Point Numbers 3.6 Wrap-Up ⎙ Print + Share This < Back Page 4 of 6 Next > This chapter is from the book This chapter is from the book Java SE8 for Programmers, 3rd EditionJava SE8 for Programmers, 3rd Edition Learn More Buy This chapter is from the book Java SE8 for Programmers, 3rd EditionJava SE8 for Programmers, 3rd Edition Learn More Buy 3.4 Account Class: Initializing Objects with Constructors As mentioned in Section 3.2, when an object of class Account (Fig. 3.1) is created, its String instance variable name is initialized to null by default. But what if you want to provide a name when you create an Account object? Each class you declare can optionally provide a constructor with parameters that can be used to initialize an object of a class when the object is created. Java requires a constructor call for every object that's created, so this is the ideal point to initialize an object's instance variables. The next example enhances class Account (Fig. 3.5) with a constructor that can receive a name and use it to initialize instance variable name when an Account object is created (Fig. 3.6). Fig. 3.5 | Account class with a constructor that initializes the name. 1 // Fig. 3.5: Account.java 2 // Account class with a constructor that initializes the name. 3 4 public class Account 5 { 6 private String name; // instance variable 7 8 // constructor initializes name with parameter name 9 public Account(String name) // constructor name is class name 10 { 11 this.name = name; 12 } 13 14 // method to set the name 15 public void setName(String name) 16 { 17 this.name = name; 18 } 19 20 // method to retrieve the name 21 public String getName() 22 { 23 return name; 24 } 25 } // end class Account Fig. 3.6 | Using the Account constructor to initialize the name instance variable at the time each Account object is created. 1 // Fig. 3.6: AccountTest.java 2 // Using the Account constructor to initialize the name instance 3 // variable at the time each Account object is created. 4 5 public class AccountTest 6 { 7 public static void main(String[] args) 8 { 9 // create two Account objects 10 Account account1 = new Account(,"Jane Green"); 11 Account account2 = new Account("John Blue"); 12 13 // display initial value of name for each Account 14 System.out.printf("account1 name is: %s%n", account1.getName()); 15 System.out.printf("account2 name is: %s%n", account2.getName()); 16 } 17 } // end class AccountTest account1 name is: Jane Green account2 name is: John Blue 3.4.1 Declaring an Account Constructor for Custom Object Initialization When you declare a class, you can provide your own constructor to specify custom initialization for objects of your class. For example, you might want to specify a name for an Account object when the object is created, as in line 10 of Fig. 3.6: Account account1 = new Account("Jane Green"); In this case, the String argument "Jane Green" is passed to the Account object's constructor and used to initialize the name instance variable. The preceding statement requires that the class provide a constructor that takes only a String parameter. Figure 3.5 contains a modified Account class with such a constructor. Account Constructor Declaration Lines 9-12 of Fig. 3.5 declare Account's constructor. A constructor must have the same name as the class. A constructor's parameter list specifies that the constructor requires one or more pieces of data to perform its task. Line 9 indicates that the constructor has a String parameter called name. When you create a new Account object (as you'll see in Fig. 3.6), you'll pass a person's name to the constructor, which will receive that name in the parameter name. The constructor will then assign name to instance variable name in line 11. Error-Prevention Tip 3.2error_prevention_tip.jpg Even though it's possible to do so, do not call methods from constructors. We'll explain this in Chapter 10, Object-Oriented Programming: Polymorphism and Interfaces. Parameter name of Class Account's Constructor and Method setName Recall from Section 3.2.1 that method parameters are local variables. In Fig. 3.5, the constructor and method setName both have a parameter called name. Although these parameters have the same identifier (name), the parameter in line 9 is a local variable of the constructor that's not visible to method setName, and the one in line 15 is a local variable of setName that's not visible to the constructor. 3.4.2 Class AccountTest: Initializing Account Objects When They're Created The AccountTest program (Fig. 3.6) initializes two Account objects using the constructor. Line 10 creates and initializes the Account object account1. Keyword new requests memory from the system to store the Account object, then implicitly calls the class's constructor to initialize the object. The call is indicated by the parentheses after the class name, which contain the argument "Jane Green" that's used to initialize the new object's name. The class instance creation expression in line 10 returns a reference to the new object, which is assigned to the variable account1. Line 11 repeats this process, passing the argument "John Blue" to initialize the name for account2. Lines 14-15 use each object's getName method to obtain the names and show that they were indeed initialized when the objects were created. The output shows different names, confirming that each Account maintains its own copy of instance variable name. Constructors Cannot Return Values An important difference between constructors and methods is that constructors cannot return values, so they cannot specify a return type (not even void). Normally, constructors are declared public—later in the book we'll explain when to use private constructors. Default Constructor Recall that line 13 of Fig. 3.2 Account myAccount = new Account(); used new to create an Account object. The empty parentheses after "new Account" indicate a call to the class's default constructor—in any class that does not explicitly declare a constructor, the compiler provides a default constructor (which always has no parameters). When a class has only the default constructor, the class's instance variables are initialized to their default values. In Section 8.5, you'll learn that classes can have multiple constructors. There's No Default Constructor in a Class That Declares a Constructor If you declare a constructor for a class, the compiler will not create a default constructor for that class. In that case, you will not be able to create an Account object with the class instance creation expression new Account() as we did in Fig. 3.2—unless the custom constructor you declare takes no parameters. Software Engineering Observation 3.3software_engineering_observation.jpg Unless default initialization of your class's instance variables is acceptable, provide a custom constructor to ensure that your instance variables are properly initialized with meaningful values when each new object of your class is created. Adding the Constructor to Class Account's UML Class Diagram The UML class diagram of Fig. 3.7 models class Account of Fig. 3.5, which has a constructor with a String name parameter. Like operations, the UML models constructors in the third compartment of a class diagram. To distinguish a constructor from the class's operations, the UML requires that the word "constructor" be enclosed in guillemets (« and ») and placed before the constructor's name. It's customary to list constructors before other operations in the third compartment. Fig. 3.7 Fig. 3.7 | UML class diagram for Account class of Fig. 3.5.

How to write an if-else-statement.

Java if, if...else Statement In this article, you will learn to use two selection statements: if and if...else to control the flow of your program's execution. In programming, it's often desirable to execute a certain section of code based upon whether the specified condition is true or false (which is known only during the run time). For such cases, control flow statements are used. Java if (if-then) Statement The syntax of if-then statement in Java is: if (expression) { // statements } Here expression is a boolean expression (returns either true or false). If the expression is evaluated to true, statement(s) inside the body of if (statements inside parenthesis) are executed. If the expression is evaluated to false, statement(s) inside the body of if are skipped from execution. How if statement works? How if statement works in Java? Example 1: Java if Statement class IfStatement { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("Number is positive."); } System.out.println("This statement is always executed."); } } When you run the program, the output will be: Number is positive. This statement is always executed. When number is 10, the test expression number > 0 is evaluated to true. Hence, codes inside the body of if statements are executed. Now, change the value of number to a negative integer. Let's say -5. The output in this case will be: This statement is always executed. When number is -5, the test expression number > 0 is evaluated to false. Hence, Java compiler skips the execution of body of if statement. To learn more about test expression and how it is evaluated, visit relational and logical operators. Java if...else (if-then-else) Statement The if statement executes a certain section of code if the test expression is evaluated to true. The if statement may have an optional else block. Statements inside the body of else statement are executed if the test expression is evaluated to false. The syntax of if-then-else statement is: if (expression) { // codes } else { // some other code } How if...else statement works? How if...else statement works in Java? Example 2: Java if else Statement class IfElse { public static void main(String[] args) { int number = 10; if (number > 0) { System.out.println("Number is positive."); } else { System.out.println("Number is not positive."); } System.out.println("This statement is always executed."); } } When you run the program, the output will be: Number is positive. This statement is always executed. When number is 10, the test expression number > 0 is evaluated to true. In this case, codes inside the body of if are executed, and codes inside the body of else statements are skipped from execution. Now, change the value of number to a negative number. Let's say -5. The output in this case will be: Number is not positive. This statement is always executed. When number is -5, the test expression number > 0 is evaluated to false. In this case, codes inside the body of else are executed, and codes inside the body of if statements are skipped from execution. Java if..else..if Statement In Java, it's possible to execute one block of code among many. For that, you can use if..else...if ladder. if (expression1) { // codes } else if(expression2) { // codes } else if (expression3) { // codes } . . else { // codes } The if statements are executed from the top towards the bottom. As soon as the test expression is true, codes inside the body of that if statement is executed. Then, the control of program jumps outside if-else-if ladder. If all test expressions are false, codes inside the body of else is executed. Example 3: Java if..else..if Statement class Ladder { public static void main(String[] args) { int number = 0; if (number > 0) { System.out.println("Number is positive."); } else if (number < 0) { System.out.println("Number is negative."); } else { System.out.println("Number is 0."); } } } When you run the program, the output will be: Number is 0. When number is 0, both test expression number > 0 and number < 0 is evaluated to false. Hence, the statement inside the body of else is executed. The above program checks whether number is positive, negative or 0. Java Nested if..else Statement It's possible to have if..else statements inside a if..else statement in Java. It's called nested if...else statement. Here's a program to find largest of 3 numbers: Example 4: Nested if...else Statement class Number { public static void main(String[] args) { Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber; if (n1 >= n2) { if (n1 >= n3) { largestNumber = n1; } else { largestNumber = n3; } } else { if (n2 >= n3) { largestNumber = n2; } else { largestNumber = n3; } } System.out.println("Largest number is " + largestNumber); } } When you run the program, the output will be: Largest number is 4.5 Note: In above programs, we have assigned value of variables ourselves to make this easier. However, in real world applications, these values may come from user input data, log files, form submission etc. You should also check ternary operator in Java, which is kind of shorthand notation of if...else statement.

What the real contents of a variable of class type are.

Java 101: Classes and objects in Java Learn how to make classes, fields, methods, constructors, and objects work together in your Java applications MORE LIKE THIS Java 101: Elementary Java language features speech bubble Java 101: Deciding and iterating with Java statements Java 101: Evaluate Java expressions with operators RELATED ARTICLES Java / JVM / flavors / flavours What to do when free Java 8 updates end coffee cup - coffee beans - Java 13 Java frameworks for rock-solid microservices java giftbox present gift surprise programmer code laptop devops Clojure 1.10 upgrade supports modern Java See all Insider Java 101: Foundations Java 101: Learn Java from the ground up Java 101: Elementary Java language... Java 101: Evaluate Java expressions... Java 101: Deciding and iterating with... Java 101: Classes and objects in Java SHOW MORE Classes, fields, methods, constructors, and objects are the building blocks of object-based Java applications. This article will teach you how to declare classes, describe attributes via fields, describe behaviors via methods, initialize objects via constructors, and instantiate objects from classes and access their members. Along the way you'll also learn about setters and getters, method overloading, setting access levels for fields, constructors, and methods, and more. If you want to go a little further with fields and methods, you may also download the free Java 101 primer showcasing constants, recursion, and other techniques in object-based programming. What is an object-based application? An object-based Java application is a Java application whose design is based on declaring classes, creating objects from them, and designing interactions between these objects. download Download the source code Source code for "Java 101: Classes and objects in Java." Created by Jeff Friesen for JavaWorld. Class declaration A class is a template for manufacturing objects. You declare a class by specifying the class keyword followed by a non-reserved identifier that names it. A pair of matching open and close brace characters ({ and }) follow and delimit the class's body. This syntax appears below: class identifier { // class body } By convention, the first letter of a class's name is uppercased and subsequent characters are lowercased (for example, Employee). If a name consists of multiple words, the first letter of each word is uppercased (such as SavingsAccount). This naming convention is called camelcasing. The following example declares a class named Book: class Book { // class body } A class's body is populated with fields, methods, and constructors. Combining these language features into classes is known as encapsulation. This capability lets us program at a higher level of abstraction (classes and objects) rather than focusing separately on data structures and functionality. Utility classes A class can be designed to have nothing to do with object manufacturing. Instead, it exists as a placeholder for class fields and/or class methods. Such a class is known as a utility class. An example of a utility class is the Java standard class library's Math class. See the Fields and methods in Java primer for another example. Multi-class applications and main() A Java application is implemented by one or more classes. Small applications can be accommodated by a single class, but larger applications often require multiple classes. In that case one of the classes is designated as the main class and contains the main() entry-point method. For example, Listing 1 presents an application built using three classes: A, B, and C; C is the main class. Listing 1. A Java application with multiple classes class A { } class B { } class C { public static void main(String[] args) { System.out.println("Application C entry point"); } } You could declare these three classes in a single source file, such as D.java. You would then compile this source file as follows: [ Learn Java from beginning concepts to advanced design patterns in this comprehensive 12-part course! ] javac D.java The compiler generates three class files: A.class, B.class, and C.class. Run this application via the following command: java C You should observe the following output: Application C entry point Alternatively, you could declare each class in its own source file. By convention, the source file's name matches the class name. You would declare A in A.java, for instance. You could then compile these source files separately: javac A.java javac B.java javac C.java To save time, you could compile all three source files at once by replacing the file name with an asterisk (but keep the .java file extension): javac *.java Either way, you would run the application via the following command: java C Public classes Java lets you declare a class with public access via the public keyword. When you declare a class public, you must store it in a file with the same name. For example, you would store public class C {} in C.java. You may declare only one public class in a source file. When designing multi-class applications, you will designate one of these classes as the main class and locate the main() method in it. However, there is nothing to prevent you from declaring main() methods in the other classes, perhaps for testing purposes. This technique is shown in Listing 2. Listing 2. Declaring more than one main() method class A { public static void main(String[] args) { System.out.println("Testing class A"); } } class B { public static void main(String[] args) { System.out.println("Testing class B"); } } class C { public static void main(String[] args) { System.out.println("Application C entry point"); } } After compiling the source code, you would execute the following commands to test the helper classes A and B, and to run the application class C: java A java B java C You would then observe the following lines of output, one line per java command: Testing class A Testing class B Application C entry point Be careful with main() Placing a main() method in each class can be confusing, especially if you forget to document the main class. Also, you might forget to remove these methods before putting the application into production, in which case their presence would add bulk to the application. Furthermore, someone might run one of the supporting classes, which could disrupt the application's environment. Fields: Describing attributes A class models a real-world entity in terms of state (attributes). For example, a vehicle has a color and a checking account has a balance. A class can also include non-entity state. Regardless, state is stored in variables that are known as fields. A field declaration has the following syntax: [static] type identifier [ = expression ] ; A field declaration optionally begins with keyword static (for a non-entity attribute) and continues with a type that's followed by a non-reserved identifier that names the field. The field can be explicitly initialized by specifying = followed by an expression with a compatible type. A semicolon terminates the declaration. The following example declares a pair of fields in Book: class Book { String title; int pubYear; // publication year } The title and pubYear field declarations are identical to the variable declarations I presented in "Java 101: Elementary Java language features." These fields are known as instance fields because each object contains its own copy of them. The title and pubYear fields store values for a specific book. However, you might want to store state that is independent of any particular book. For example, you might want to record the total number of Book objects created. Here's how you would do it: class Book { // ... static int count; } This example declares a count integer field that stores the number of Book objects created. The declaration begins with the static keyword to indicate that there is only one copy of this field in memory. Each Book object can access this copy, and no object has its own copy. For this reason, count is known as a class field. Initialization The previous fields were not assigned values. When you don't explicitly initialize a field, it's implicitly initialized with all of its bits set to zero. You interpret this default value as false (for boolean), '\u0000' (for char), 0 (for int), 0L (for long), 0.0F (for float), 0.0 (for double), or null (for a reference type). However, it is also possible to explicitly initialize a field when the field is declared. For example, you could specify static int count = 0; (which isn't necessary because count defaults to 0), String logfile = "log.txt";, static int ID = 1;, or even double sinPIDiv2 = Math.sin(Math.PI / 2);. Although you can initialize an instance field through direct assignment, it's more common to perform this initialization in a constructor, which I'll demonstrate later. In contrast, a class field (especially a class constant) is typically initialized through direct assignment of an expression to the field. Lifetime and scope An instance field is born when its object is created and dies when the object is garbage collected. A class field is born when the class is loaded and dies when the class is unloaded or when the application ends. This property is known as lifetime. Instance and class fields are accessible from their declarations to the end of their declaring classes. Furthermore, they are accessible to external code in an object context only (for instance fields) or object and class contexts (for class fields) when given suitable access levels. This property is known as scope. Methods: Describing behaviors In addition to modeling the state of a real-world entity, a class also models its behaviors. For example, a vehicle supports movement and a checking account supports deposits and withdrawals. A class can also include non-entity behaviors. Regardless, Java programmers use methods to describe behaviors. A method declaration has the following syntax: [static] returnType identifier ( [parameterList] ) { // method body } A method declaration optionally begins with keyword static (for a non-entity behavior) and continues with a returnType that's followed by a non-reserved identifier that names the method. The name is then followed by a round bracket-delimited optional parameterList. A brace-delimited body containing code to execute when the method is called follows. The return type identifies the type of values that are returned from the method via the return statement, which I'll discuss later. For example, if a method returns strings, its return type would be set to String. When a method doesn't return a value, its return type is set to void. The parameter list is a comma-separated list of parameter declarations: each declaration consists of a type followed by a non-reserved identifier that names the parameter. A parameter is a variable that receives an argument (an expression value whose type is compatible with its corresponding parameter) when a method or constructor is called. A parameter is local to its method or constructor. It comes into existence when the method or constructor is called and disappears when the method or constructor returns to its caller. In other words, its lifetime is the method execution. A parameter can be accessed by any code within the method. Its scope is the entire method. The following example declares four methods in the Book class: class Book { // ... String getTitle() { return title; } int getPubYear() { return pubYear; } void setTitle(String _title) { title = _title; } void setPubYear(int _pubYear) { pubYear = _pubYear; } } The getTitle() and getPubYear() methods return the values of their respective fields. They use the return statement to return these values to the caller. Note that the type of this statement's expression must be compatible with the method's return type. The setTitle() and setPubYear() methods let you set the values of the title and pubYear fields. Their return types are set to keyword void to indicate that they don't return any values to their callers. All four methods are known as instance methods because they affect only the objects on which they are called. Setters and getters The "set" prefix identifies setTitle() and setPubYear() as setter methods, meaning that they set values. Similarly, the "get" prefix identifies getTitle() and getPubYear() as getter methods, which means that they get values. If you're wondering about the need for setter/getter methods in lieu of directly accessing title and pubYear, you'll find some good reasons in the "What is the point of getters and setters?" topic at StackOverflow.com. The getTitle(), getPubYear(), setTitle(), and setPubYear() methods affect a single object's copies of the title and pubYear fields. However, you might want to declare a method that's independent of any particular book. For example, you might want to introduce a method that outputs the number of Book objects, as follows: class Book { // ... static void showCount() { System.out.println("count = " + count); } } This example declares a showCount() method that will output the value of the count field. The declaration begins with the static keyword to indicate that this method belongs to the class and cannot access individual object state; no objects need to be created. For this reason, showCount() is known as a class method. Local variables Within a method or constructor, you can declare additional variables as part of its implementation. These variables are known as local variables because they are local to the method/constructor. They exist only while the method or constructor is executing and cannot be accessed from outside the method/constructor. Consider the following example: static void average(double[] values) { double sum = 0.0; for (int i = 0; i < values.length; i++) sum += values[i]; System.out.println("Average: " + (sum / values.length)); }

What a boolean expression is

A boolean type can have one of two values: true or false. ... In Java, you can't convert between an integer type and a boolean type. A Boolean expression is a Java expression that, when evaluated, returns a Boolean value: true or false. Boolean expressions are used in conditional statements, such as if, while, and switch.

What formal parameters (parameter variables) are, what actual arguments are, and how they correspond to one another

A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters. Parameter is variable in the declaration of function. Argument is the actual value of this variable that gets passed to function.

How to define fields and methods in a class (with appropriate access modifiers)

Access Modifiers in Java As the name suggests access modifiers in Java helps to restrict the scope of a class, constructor , variable , method or data member. There are four types of access modifiers available in java: Default - No keyword required Private Protected Public access-modifiers-in-java Default: When no access modifier is specified for a class , method or data member - It is said to be having the default access modifier by default. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package. In this example, we will create two packages and the classes in the packages will be having the default access modifiers and we will try to access a class from one package from a class of second package. filter_none edit play_arrow brightness_4 //Java program to illustrate default modifier package p1; //Class Geeks is having Default access modifier class Geek { void display() { System.out.println("Hello World!"); } } filter_none edit play_arrow brightness_4 //Java program to illustrate error while //using class from different package with //default modifier package p2; import p1.*; //This class is having default access modifier class GeekNew { public static void main(String args[]) { //accessing class Geek from package p1 Geeks obj = new Geek(); obj.display(); } } Output: Compile time error Private: The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Any other class of same package will not be able to access these members. Top level Classes or interface can not be declared as private because private means "only visible within the enclosing class". protected means "only visible within the enclosing class and any subclasses" Hence these modifiers in terms of application to classes, they apply only to nested classes and not on top level classes In this example, we will create two classes A and B within same package p1. We will declare a method in class A as private and try to access this method from class B and see the result. filter_none edit play_arrow brightness_4 //Java program to illustrate error while //using class from different package with //private modifier package p1; class A { private void display() { System.out.println("GeeksforGeeks"); } } class B { public static void main(String args[]) { A obj = new A(); //trying to access private method of another class obj.display(); } } Output: error: display() has private access in A obj.display(); protected: The protected access modifier is specified using the keyword protected. The methods or data members declared as protected are accessible within same package or sub classes in different package. In this example, we will create two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method display in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B. filter_none edit play_arrow brightness_4 //Java program to illustrate //protected modifier package p1; //Class A public class A { protected void display() { System.out.println("GeeksforGeeks"); } } filter_none edit play_arrow brightness_4 //Java program to illustrate //protected modifier package p2; import p1.*; //importing all classes in package p1 //Class B is subclass of A class B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); } } Output: GeeksforGeeks public: The public access modifier is specified using the keyword public. The public access modifier has the widest scope among all other access modifiers. Classes, methods or data members which are declared as public are accessible from every where in the program. There is no restriction on the scope of a public data members. filter_none edit play_arrow brightness_4 //Java program to illustrate //public modifier package p1; public class A { public void display() { System.out.println("GeeksforGeeks"); } } package p2; import p1.*; class B { public static void main(String args[]) { A obj = new A; obj.display(); } } Output: GeeksforGeeks Important Points: If other programmers use your class, try to use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to. Avoid public fields except for constants. This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Recommended Posts: Access and Non Access Modifiers in Java Access Modifiers in C++ Access specifiers for classes or interfaces in Java Java | CDMA (Code Division Multiple Access) More restrictive access to a derived class method in Java Method Overriding with Access Modifier Access specifier of methods in interfaces Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java Java.util.Collections.disjoint() Method in java with Examples Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java Java lang.Long.byteValue() method in Java with Examples Java lang.Long.numberOfTrailingZeros() method in Java with Examples Java lang.Long.lowestOneBit() method in Java with Examples Java lang.Long.reverse() method in Java with Examples

The eight primitive data types, and which ones we are using in this course

Variables and the 8 Primitive Data Types The Purpose of a Variable (and some vocabulary) You can think of a simple program as a list of instructions to be read and acted upon sequentially Example: Read a value representing the radius of a circle from the standard input source/stream Compute the area of a circle with this radius Print the area to the standard output stream (i.e., the console window) Remember: a computer will read and act upon these instructions one at a time - it is not aware of what is coming up until it gets there! Looking at step 1 in the program above, we will need to tell the computer that it needs to remember the value it is reading in - it needs to store this value in its memory somewhere so we can use it in a computation later. We need to tell the computer how much memory will be needed to store the value in question. Different kinds of numbers require different amounts of memory (more on this in a minute). Of course, we sometimes need to store things other than numbers. These things too, come in different sizes. For example, it will certainly take more memory to store the Declaration of Independence than it will to store a single letter (i.e., a "character"). Further, we also need to tell the computer how the value should be stored in memory (i.e., what method of "encoding" should be employed to turn the value into a string of 1's and 0's). Examples of types of encodings used include Two's Complement, IEEE 754 Form, ASCII, Unicode, etc... The computer also needs to have some reference to where it stored the value, so it can find it again. The concept of a variable solves all of our problems here. A variable in Java gives us a way to store values (or other kinds of information) for later use, addressing all of the aforementioned considerations. The amount of memory allocated for a given variable and how the value of that variable should be stored in memory depends upon its type. There are 8 primitive types of data built into the Java language. These include: int, byte, short, long, float, double, boolean, and char. The first 6 allow for storage of different kinds of numbers, the last stores a single character (think "keyboard" character). We'll talk more about the differences between these in a little bit... Also, every variable has a name that refers to the location of that particular portion of memory (so the computer can find it again). And of course, the value of a variable consists of whatever information currently occupies the memory referenced by its name. Whenever we use a variable in a Java program, we must first declare the variable - that is, we specify what the type and name of the variable will be. Then we can assign a value to the variable - that is, tell it what to remember. When we assign a variable a value for the first time, we are said to be initializing the variable. Of course, computers are picky about how you tell them to do something. Truth be told, they are kind of dumb. They can't "read between the lines" or "figure out what you really meant". Programming languages have a particular format you have to stick to when telling the computer what to do. This format is called syntax. When code is written in a way that the computer can understand, we say the code is syntactically correct. When the code is written in a way the computer cannot understand, we say there is a syntax error. Let's take a look at the syntax for declaring a variable: <variableType> <variableName>; Two Examples: int myLuckyNumber; //Declares myLuckyNumber to be an integer variable char myLetter; //Declares myLetter to be a character variable The semicolon on the end functions much like a period does in the English language. It tells the computer that the statement of what to do is complete at this point. Declare this variable of this type (that is to say: tell the computer to allocate an appropriate amount of memory for the type of variable given and reference that portion of memory by the name given), and that's it. Now move on to the next statement... To assign a variable a value, we use the following syntax: <variableName> = <value or expression>; Some Examples: myLuckyNumber = 13; //Assigns the variable myLuckyNumber //the value 13 myLuckyNumber = 5+8; //Also assigns the variable myLuckyNumber //the value 13 //Note: expressions like the sum on the //right are evaluated before they are //assigned myLetter = 'a'; //Assigns the variable myLetter the //character 'a'. Note the equals sign here means something different than it does in mathematics. In fact, we don't even call this symbol "equals". We call it the "assignment operator" instead, or "gets" for short. So we read the following: myLuckyNumber = 13; as "The variable myLuckyNumber gets the value 13." A Useful Shortcut -- Variable Declaration and Assignment in One Statement Java does allow us to shorten variable declaration and initialization up a bit, syntactically. We can declare a variable and assign it a value in one step as the following examples show: int x = 1; double d = 1.4; char myLetter = 'a'; int myLuckyNumber = 5 + 8; double myProduct = 3.14 * (2.78 + 1.0); When source code contains a representation of a fixed value (like 1, 1.4, and 'a' above) that requires no computation, we call that representation a literal. An expression, on the other hand, (like the 5+8 or the 3.14 * (2.78 + 1.0) above) is a combination of one or more operands and operators, whose value must be calculated. The operands might be literals, variables, or some other source of data. Variable Reassignment Variables don't have to have the same value throughout your entire program. Their contents can be changed over the course of the program's execution. For example, suppose you are writing a program to count the number of stars seen in an image of the night sky taken with your digital camera. You might declare a variable named "numStarsFound", initializing it to zero. Then upon examining the picture file, each time your program locates a new star, you might increase the value of your variable by one with the following statement: numStarsFound = numStarsFound + 1; Then when you are done, the variable numStarsFound will reflect the number of stars found in the entire picture. Be aware, you must declare a variable before you can assign a value to it, but you should only declare a variable once within a given scope. (We'll talk more about scope later.) Printing the Value of a Variable As seen in the "Hello World" program, we can use System.out.println() to print things to the console. The "things" that can be printed include text, variable values, or the value of any valid expression. As an example, suppose one wants to print the value of a previously declared and initialized variable named myVar. The following would do the trick: System.out.println(myVar); Technically, the code above does a little bit more than just printing the value of myVar -- it also prints a line-feed character immediately afterwards. The effect of this is similar to hitting the "return" key on a keyboard, it moves the cursor down a line. As such, if anything is printed to the console after this statement, it will be printed on a different line. If you wanted to avoid printing the extra line-feed character, you could opt for System.out.print() instead, as the example below suggests. int a = 1; int b = 2; System.out.println(a); System.out.println(b); System.out.print(a); System.out.print(b); The above code snippet would print the following to the console: 1 2 12 Here's an example that mixes in some re-assignments and also prints variable values of different types. Note in particular how the double z gets printed as a decimal, despite it not having a fractional part... int x = 1; //an integer variable x is declared //and initialized to 1 int y = 2; //an integer variable y is declared //and initialized to 2 double z = 3; //a double variable z is declared //and initialized to 3.0 x = y + 3; //x is now 5 y = x * 4; //y is now 20 x = x + 1; //x is now 6 System.out.print(x); //prints 6 to the console System.out.println(y); //prints 20 to the console System.out.println(z); //prints 3.0 to the console Here's what we would see on the console when the above code is executed: 620 3.0 The Names of Variables... The name of a variable is formally called an identifier. Identifiers are sequences of characters, consisting only of letters, digits, underscores (_), and/or dollar signs($). An identifier must start with a letter, an underscore (_), or a dollar sign ($). It must not start with a digit. Identifier names are case sensitive!!! (mynumber is different than myNumber) An identifier may not be a reserved word, or the words: true, false, or null. Here's a list of the reserved words in the Java programming language. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like reserved, but they are actually literals (i.e., values like 0, 3.14, or 'a'); you cannot use them as identifiers in your programs either. abstract continue for new switch assert*** default goto* package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum**** instanceof return transient catch extends int short try char final interface static void class finally long strictfp** volatile const* float native super while (* not used; ** added in Java 1.2; *** added in Java 1.4; **** added in Java 5) Conventions for Identifiers The computer doesn't care about the following rules, but your instructor and any other programmer (including you) that has to read your code will! Variable names should start with a lowercase letter Class names (which also have identifiers that follow the same syntactical guidelines should start with an uppercase letter Meaningful names should be used If an identifier is to be made up of more than one word, CamelCase should be used (e.g., "myLuckyNumber") The 8 Primitive Variable Types Depending on the nature of the information one wishes to store in a variable, and -- in the case of numerical information -- depending the size and precision required, one can use any of the following eight primitive types in Java: byte, short, int, long,float,double,char,boolean. For the 6 numerical types, we have the following ranges, storage size, and encoding methods: Name Range Storage Size (and Method) byte ‐128 to 127 (i.e., ‐27 to 27 - 1) 8 bits (Two's Complement) short ‐32768 to 32767 (i.e., ‐215 to 215 - 1) 16 bits (Two's Complement) int ‐2147483648 to 2147483647 (i.e., ‐231 to 231 - 1) 32 bits (Two's Complement) long ‐9223372036854775808 to 9223372036854775807 (i.e., -263 to 263 - 1) 64 bits (Two's Complement) float Negative range: ‐3.4028235E+38 to ‐1.4E‐45 Positive range: 1.4E‐45 to 3.4028235E+38 32 bits (IEEE 754 Notation) double Negative range: ‐1.7976931348623157E+308 to ‐4.9E‐324 Positive range: 4.9E‐324 to 1.7976931348623157E+308 64 bits (IEEE 754 Notation) Note: float and double number types are stored in IEEE 754 format, and thus not stored with complete accuracy due to approximations. To convince yourself of this, try the following System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); and... System.out.println(1.0 - 0.9);

Understand the logic of nested conditionals (nested ifs).

It is always legal to nest if-else statements which means you can use one if or else if statement inside another if or else if statement. Syntax The syntax for a nested if...else is as follows − if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } You can nest else if...else in the similar way as we have nested if statement. Example Live Demo public class Test { public static void main(String args[]) { int x = 30; int y = 10; if( x == 30 ) { if( y == 10 ) { System.out.print("X = 30 and Y = 10"); } } } } This will produce the following result − Output X = 30 and Y = 10

What sequential and conditional processing are.

Unit 5 Conditional statements Summary • The if-else and if statements • Block of statements • Conditional expression • Comparison between objects • The switch statement 5.1 Statements in Java Till now we have seen two types of executable statements (without counting declarations): • method invocation • assignment These are simple statements by means of which we can write programs • constituted by sequences of simple statements; • that do method calls, possibly nested. Very often, when we have to solve a problem, we are interested in performing different actions depending on whether certain conditions are true or false. 5.2 Conditional statements Java, like all other programming languages, is equipped with specific statements that allow us to check a condition and execute certain parts of code depending on whether the condition is true or false. Such statements are called conditional, and are a form of composite statement. In Java, there are two forms of conditional statements: • the if-else statement, to choose between two alternatives; • the switch statement, to choose between multiple alternatives. 5.3 The if-else statement The if-else statement allows us to select between two alternatives. if-else statement Syntax: if (condition ) then-statement else else-statement • condition is an expression of type boolean, i.e., a conditional expression that is evaluated to true or false • then-statement is a single statement (also called the then-branch of the if-else statement) • else-statement is a single statement (also called the else-branch of the if-else statement) 1 2 UNIT 5 Semantics: First, the condition is evaluated. If the result of the evaluation is the value true, the then-statement is executed, otherwise the else-statement is executed. In both cases, the execution continues with the statement immediately following the if-else statement. Example: int a, b; ... if (a > b) System.out.println("bigger value = " + a); else System.out.println("bigger value = " + b); When this if-else statement is executed, the string "bigger value = " followed by the bigger one among a and b is printed on the output channel (the monitor). 5.4 Condition in an if-else statement The condition in an if-else statement can be an arbitrary expression of type boolean, for example: • a variable of type boolean; Example: boolean finished; ... if (finished) ... • one of the comparison operators (==, !=, >, <, >=, or <=) applied to variables (or expressions) of a primitive type; Example: int a, b, c; ... if (a > b + c) ... • a call to a predicate (i.e., a method that returns a value of type boolean); Example: String answer; ... if (answer.equalsIgnoreCase("YES")) ... • a complex boolean expression, obtained by applying the boolean operators !, &&, and || to simpler expressions; Example: int a, b, c, d; String answer; ... if ((a > (b+c)) || (a == d) && !answer.equalsIgnoreCase("YES")) ... 5.5 The if variant The else part of an if-else statement is optional. If it is missing, we have an if statement, which allows us to execute a certain part of code if a condition is satisfied (and do nothing otherwise). if statement Syntax: °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 3 if (condition ) then-statement • condition is an expression of type boolean • then-statement is a single statement (also called the then-branch of the if statement) Semantics: First, the condition is evaluated. If the result of the evaluation is the value true, the then-statement is executed, and the execution continues with the statement immediately following the if statement. Otherwise, the execution continues directly with the statement following the if statement. Example: boolean found; ... if (!found) System.out.println("element not found"); When this if statement is executed, the string "element not found" is printed on the output channel, provided the value of the boolean variable found is false. 5.6 Block of statements The syntax of if-else allows us to have only a single statement in the then-branch (or the else-branch). If we want to execute more than one statement in the then-branch (or the else-branch), we have to use a block construct. A block of statements groups several statements in a single composite statement. Block of statements Syntax: { statement ... statement } • statement is an arbitrary Java statement Semantics: The statements in the block are executed in sequence. The variables declared inside the block are not visible outside the block itself. Example: int a, b, bigger; ... if (a > b) { bigger = a; System.out.println("smaller = " + b); } 5.7 Scope of variables defined in a block A block of statements can contain variable declarations. The scope of a variable declared inside a block is the block itself, including other blocks contained in it, if present. This means that the variable is visible in the block and in all sub-blocks, but is not visible outside the block. Example: public class ScopeInBlock { public static void main(String[] args) { String a = "Hello"; °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 4 UNIT 5 int i = 1; { System.out.println(a); // OK. a is visible - prints Hello //int i; // ERROR. i is visibile and cannot be redeclared { double r = 5.5; // OK i = i + 1; // OK. i is still visible System.out.println(r); // OK. r is visible - prints 5.5 } //System.out.println(r); // ERROR. r is not visible System.out.println(i); // OK. i is visibile - prints 2 { int r = 4; // OK. previous r is not visible anymore System.out.println(a); // OK. a is still visibile - prints Hello } } i = i + 1; // OK. i is visible System.out.println(i); // OK. i is visible - prints 3 } } 5.8 Use of blocks in an if-else statement The then-branch or the else-branch of an if-else statement can be any Java statement, and in particular it can be a block. Example: Given month and year, compute month and year of the next month. int month, year, nextMonth, nextYear; ... if (month == 12) { nextMonth = 1; nextYear = year + 1; } else { nextMonth = month + 1; nextYear = year; } 5.9 Nested if 's We have a nested if when the then-branch or the else-branch of an if-else statement is again an if-else or an if statement. Example: Given day, month, and year, compute day, month, and year of the next day. int day, month, year, nextDay, nextMonth, nextYear; ... if (month == 12) { if (day == 31) { nextDay = 1; nextMonth = 1; nextYear = year + 1; } else { nextDay = Day + 1; nextMonth = month; °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 5 nextYear = year; } } else { ... } 5.10 Nested if 's with mutually excluding conditions A common use of nested if's is when the conditions in the nested if's are mutually excluding, i.e., no two of them can be simultaneously true. Example: Based on the value of the temperature (an integer) print a message according to the following table: temperature t message 30 < t hot 20 < t ≤ 30 warm 10 < t ≤ 20 fine t ≤ 10 cold int temp; ... if (30 < temp) System.out.println("hot"); else if (20 < temp) System.out.println("warm"); else if (10 < temp) System.out.println("fine"); else System.out.println("cold"); Observations: • At the outermost level we have a single if-else statement. • The order in which the conditions are specified is important. • The second condition need not be composite, e.g., (20 < temp) && (temp <= 30), since it appears in the else-branch of the first condition. Hence, we already know that (temp <= 30) is true. • Each else refers to the if that immediately precedes it. 5.11 Ambiguity of the else in if-else statements Consider the following code fragment: if (a > 0) if (b > 0) System.out.println("b positive"); else System.out.println("???"); System.out.println("???") could in principle be the else-branch of: • the first if: hence we should replace "???" with "a negative"; • the second if: hence we should replace "???" with "b negative". The ambiguity is solved by considering that an else always refers to the nearest if without an associated else. In the above example we have: if (a > 0) if (b > 0) System.out.println("b positive"); else System.out.println("b negative"); It is always possible to use a block (i.e., {..}) to disambiguate nested if-else statements. In particular, if we want that an else refers to an if that is not the immediately preceding one, we have to enclose the immediately preceding if in a block. For example: °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 6 UNIT 5 if (a > 0) { if (b > 0) System.out.println("b positive"); } else System.out.println("a negative"); 5.12 Example: type of a triangle Given three values representing the lengths of the three sides of a triangle, determine whether the triangle is regular (all three sides are equal), symmetric (two sides are equal), or irregular (no two sides are equal). A possible algorithm is the following: compare the sides two by two, until we have gathered sufficient information to decide the type of the triangle. The algorithm can be implemented as follows: double first, second, third; ... if (first == second) { if (second == third) System.out.println("regular"); else System.out.println("symmetric"); } else { if (second == third) System.out.println("symmetric"); else if (first == third) System.out.println("symmetric"); else System.out.println("irregular"); } 5.13 Shortcut evaluation of a complex condition The condition in an if-else statement can be a complex boolean expression, in which the logical operators &&, ||, and ! may appear. We have seen that Java performs a shortcut evaluation of such expressions. In other words, the subexpressions to which the operators are applied are evaluated from left to right as follows: • when evaluating (e1 && e2), if the evaluation of e1 returns false, then e2 is not evaluated. • when evaluating (e1 || e2), if the evaluation of e1 returns true, then e2 is not evaluated. Consider the case of (e1 && e2). If the value of e1 is false, then the value of the whole expression (e1 && e2) is false, independently of the value of e2. This justifies why in Java e2 is not even evaluated. Similar considerations hold for (e1 || e2). In general, the fact that Java performs a shortcut evaluation of boolean expressions has to be taken into account and cannot be ignored, since the correctness of the code may depend on that. Example: String s; ... if (s != null && s.length() > 0) { System.out.println(s); } In this case, when the value of s is null then s.length()>0 is not evaluated and the method length() is not called. Note that, if Java evaluated s.length()>0 also when s is null, then the above code would be wrong, since it would cause trying to access via s a nonexistent object. Note: In general, if-else statements that make use of complex boolean conditions could be rewritten by making use of nested if-else statements. However, to do so, it may be necessary to duplicate code. We illustrate this in the following separately for && and ||. 5.14 Eliminating the conjunction operator && in a complex condition The code fragment °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 7 if ((x < y) && (y < z)) System.out.println("y is between x and z"); else System.out.println("y is not between x and z"); corresponds to if (x < y) if (y < z) System.out.println("y is between x and z"); else System.out.println("y is not between x and z"); else System.out.println("y is not between x and z"); In this case, by eliminating the complex condition, the code of the else-branch must be duplicated. Note that, due to shortcut evaluation, the second condition in the && is not evaluated if the first condition is false. And this holds also for the corresponding nested if-else statements. 5.15 Eliminating the disjunction operator || in a complex condition The code fragment if ((x == 1) || (x == 2)) System.out.println("x equal to 1 or to 2"); else System.out.println("x different from 1 and from 2"); corresponds to if (x == 1) System.out.println("x equal to 1 or to 2"); else if (x == 2) System.out.println("x equal to 1 or to 2"); else System.out.println("x different from 1 and from 2"); In this case, by eliminating the complex condition, the code of the then-branch must be duplicated. Again, due to shortcut evaluation, the second condition in the || is not evaluated if the first condition is true. And this holds also for the corresponding nested if-else statements. 5.16 Conditional expression Java is equipped with a selection operator that allows us to construct a conditional expression. The use of a conditional expression can in some cases simplify the code with respect to the use of an if-else statement. Conditional expression Syntax: condition ? expression-1 : expression-2 • condition is a boolean expression • expression-1 and expression-2 are two arbitrary expressions, which must be of the same type Semantics: Evaluate condition . If the result is true, then evaluate expression-1 and return its value, otherwise evaluate expression-2 and return its value. Example: System.out.println("bigger value = " + (a > b)? a : b); °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 8 UNIT 5 The statement in the example, which makes use of a conditional expression, is equivalent to: if (a > b) System.out.println("bigger value = " + a); else System.out.println("bigger value = " + b); Note that the selection operator is similar to the if-else statement, but it works at a different syntactic level: • The selection operator combines expressions and returns another expression. Hence it can be used wherever an expression can be used. • The if-else statement groups statements, and the result is a composite statement. 5.17 Note on comparisons: equality between strings To test whether two strings (i.e., two objects of the class String) are equal, we have to use the equals method. It would be wrong to use ==. Example: String input; ... if (input == "YES") { ... } // This is WRONG!!! if (input.equals("YES")) { ... } // This is CORRECT!!! Indeed, == tests the equality between two references to an object, and this corresponds to test the identity of the two objects (i.e., that the two objects are in fact the same object). Instead, equals tests that the two objects have the same content (i.e., that the two strings are constituted by the same sequences of characters). Example: String s = new String("pippo"); String t = new String("pippo"); String w = s; System.out.println("s == w? " + s == w); // TRUE System.out.println("s == t? " + s == t); // FALSE System.out.println("s equals t?" + s.equals(t)); // TRUE 5.18 Note on comparisons: lexicographic comparison between strings A string s precedes a string t in lexicographic order if • s is a prefix of t, or • if c and d are respectively the first character of s and t in which s and t differ, then c precedes d in character order. Note: For the characters that are alphabetical letters, the character order coincides with the alphabetical order. Digits precede letters, and uppercase letters precede lowercase ones. Example: • house precedes household • Household precedes house • composer precedes computer • H2O precedes HOTEL To verify whether a string precedes another one in lexicographic order, we use the compareTo method. Given two strings s and t, s.compareTo(t) returns • a negative integer, if s precedes t; • 0, if s is equal to t, i.e., if s.equals(t) returns true; • a positive integer, if s follows t. °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 9 5.19 Note on comparisons: equality between objects As for strings, to test whether two objects of a class are equal, we cannot use ==, because it tests the equality of the references to the two objects. Instead, we have to define a suitable method that takes into account the structure of the objects of the class. Example: Referring to the class BankAccount developed in Unit 4, we could add to such a class the definition of an predicate equalTo, which we can use to compare two bank accounts: public boolean equalTo(BankAccount ba) { return this.name.equals(ba.name) && this.surname.equals(ba.surname) && this.balance == ba.balance; } In other words, two bank accounts are considered equal if they coincide in the name and surname of the owner (this is checked using the equals method for strings) and if they have the same balance (this is checked using ==, since balance is an instance variable of the primitive type float). Example of usage: BankAccount ba1 = new BankAccount("Mario", "Rossi"); // balance is 0 BankAccount ba2 = new BankAccount("Carla", "Verdi"); // balance is 0 BankAccount ba3 = new BankAccount("Carla", "Verdi"); // balance is 0 BankAccount ba4 = ba2; System.out.println("ba1 and ba2 equal? " + ba1.equalTo(ba2)); // NO System.out.println("ba2 and ba3 equal? " + ba2.equalTo(ba3)); // YES System.out.println("ba2 and ba3 coincide? " + ba2 == ba3); // NO System.out.println("ba2 and ba4 equal? " + ba2.equalTo(ba4)); // YES System.out.println("ba2 and ba4 coincide? " + ba2 == ba4); // YES Note: Actually, there is a standard technique to define an equality predicate that is based on overriding of the method equals inherited from Object. This technique will be shown in later courses. 5.20 Note on comparisons: comparison with null We recall that a variable of type reference to object that does not refer to any object has value null. The comparison with null can be used in the condition of an if-else statement. To compare with null we have to use == and not the equals method. Example: showInputDialog returns null if the user presses the "cancel" button: String input = JOptionPane.showInputDialog("..."); if (input != null) { ... } 5.21 Exercise: modification of the class BankAccount Specification: Modify the class to handle bank accounts developed in Unit 4 in such a way that the a withdrawal is only done if enough money is available. Add also the following methods: • a method sameOwner to verify whether two objects of the class BankAccount have the same owner (i.e., the same name and surname); • a method transferTo that, given a bank account and an amount, transfers the amount to the bank account, handling also the case where not enough money is available for the transfer; • a method transferFrom that, given a bank account and an amount, transfers the amount from the bank account, handling also the case where not enough money is available for the transfer. Example of usage: public class TestBankAccount { public static void main(String[] args) { °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 10 UNIT 5 BankAccount ba1 = new BankAccount("Mario", "Rossi"); BankAccount ba2 = new BankAccount("Carla", "Verdi"); BankAccount ba3 = new BankAccount("Carla", "Verdi"); System.out.println("Do ba1 and ba2 have the same owner? " + ba1.sameOwner(ba2)); System.out.println("Do ba2 and ba3 have the same owner? " + ba2.sameOwner(ba3)); ba1.deposit(1000); ba2.deposit(500); ba3.deposit(750); System.out.println("Before the transfer ..."); System.out.println(ba1); System.out.println(ba2); ba1.transferTo(ba2, 250); System.out.println("After the transfer..."); System.out.println(ba1); System.out.println(ba2); } } 5.22 A class to handle the time of the day Specification: Design a class containing utilities to handle the time of the day, represented through hours, minutes, and, seconds. The class should define the following methods: • methods to add and subtract two times of the day, • predicates to compare two times of the day, • a method to print a time of the day. Methods of the class TimeOfDay: // constructor public TimeOfDay(int h, int m, int s) // adds a time public void add(TimeOfDay t) // subtracts a time public void subtract(TimeOfDay t) // predicate to test for precedence public boolean precedes(TimeOfDay t) // predicate to test for equality public boolean equalTo(TimeOfDay t) // method toString public String toString() Example of usage: public class TestTimeOfDay { public static void main(String[] args) { TimeOfDay t1 = new TimeOfDay(10,45,15); TimeOfDay t2 = new TimeOfDay(15,00,00); if (t1.precedes(t2)) { t1.add(new TimeOfDay(0,30,00)); } else t2.subtract(new TimeOfDay(0,30,00)); System.out.println("TimeOfDay 1 = " + t1); System.out.println("TimeOfDay 2 = " + t2); System.out.println("TimeOfDay 1 equal to TimeOfDay 2 ? " + t1.equalTo(t2)); } } °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 11 5.23 Solution of the exercise on the class TimeOfDay public class TimeOfDay { // we represent a time of the day by the total number of seconds since midnight private int totsec; public TimeOfDay(int h, int m, int s) { totsec = h*3600 + m*60 + s; } public void add(TimeOfDay t) { this.totsec += t.totsec; if (this.totsec > 24*3600) this.totsec -= 24*3600; } public void subtract(TimeOfDay t) { this.totsec -= t.totsec; if (this.totsec < 0) this.totsec += 24*3600; } public boolean precedes(TimeOfDay t) { return this.totsec < t.totsec; } public boolean equalTo(TimeOfDay t) { return this.totsec == t.totsec; } public String toString() { int h = totsec / 3600; int m = (totsec - h*3600) / 60; int s = (totsec - h*3600 - m*60); String hh = (h < 10) ? " " + h : Integer.toString(h); String mm = (m < 10) ? " " + m : Integer.toString(m); String ss = (s < 10) ? " " + s : Integer.toString(s); return hh + ":" + mm + ":" + ss; } } 5.24 The switch statement If we have to realize a multiple-choice selection we can use several nested if-else statements. Java has also a specific statement that can be used in specific cases to realize in a simpler way a multiple-choice selection. switch statement (version with break) Syntax: switch (expression ) { case label-1 : statements-1 break; ... case label-n : statements-n break; default: default-statements } • expression is an expression of an integer type or of type char • label-1 ,. . . , label-n are constant integer (or character) expressions; in other words, the expressions can contain only integer (or character) literals or constants that are initialized with constant expressions; the °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 12 UNIT 5 values of two different labels cannot coincide • statements-1 ,. . . , statements-n and default-statements are arbitrary sequences of statements • the default part is optional Semantics: 1. First, expression is evaluated. 2. Then, the first i is found for which the value of label-i is equal to the value of expression . 3. If there is such an i , then statements-i are executed; otherwise default-statements are executed. 4. The execution continues with the statement immediately following the switch statement. Example: int i; ... switch (i) { case 0: System.out.println("zero"); break; case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; default: System.out.println("less than zero or greater than two"); } When i is equal to 0 (respectively, 1, 2) then "zero" (respectively "one", "two") is printed; when i is less than 0 or greater than two, then "less than zero or greater than two" is printed. Note: If we have more than one values of the expression for which we want to execute the same statements, we can group together different cases: case label-1 : case label-2 : statements break; 5.25 Example of switch statement Computing the days of the month. int month, daysOfMonth; ... switch (month) { case 4: case 6: case 9: case 11: daysOfMonth = 30; break; case 1: case 3: case 5: case 7: case 8: case 10: case 12: daysOfMonth = 31; break; case 2: daysOfMonth = 28; break; default: daysOfMonth = 0; System.out.println("Month is not valid"); } System.out.println("Days: " + daysOfMonth); 5.26 Observation on the switch statement The expression used for the selection can be an arbitrary Java expression that returns an integer or character value (but not a floating point value). °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 13 The values specified by the various case label s must be constant expressions, i.e., their value must be known at compile time. In particular, they cannot be expressions that refer to variables. The following code fragment is wrong: int a; ... switch (a) { case a<0: System.out.println("negative"); // ERROR! a<0 is not a constant expression case 0: System.out.println("zero"); case a>0: System.out.println("positive"); // ERROR! a>0 is not a constant expression } It follows that the usefulness of the switch statement is limited. 5.27 Omission of break (optional) Actually, Java does not require that in each case of a switch statement the last statement is a break. Hence, in general, the form of a switch statement is the following. switch statement (general version) Syntax: switch (expression ) { case label-1 : statements-1 ... case label-n : statements-n default: default-statements } • expression is an expression of an integer type or of type char • label-1 ,. . . , label-n are constant integer (or character) expressions; in other words, the expressions can contain only integer (or character) literals or constants that are initialized with constant expressions; the values of two different labels cannot coincide • statements-1 ,. . . , statements-n and default-statements are arbitrary sequences of statements • the default part is optional Semantics: 1. First, expression is evaluated. 2. Then, the first i is found for which the value of label-i is equal to the value of expression . 3. If there is such an i , then statements-i , statements-i+1 , . . . are executed in sequence until the first break statement or the end of the switch statement; otherwise default-statements are executed. 4. The execution continues with the statement immediately following the switch statement. Example: More cases of a switch statement executed in sequence. int sides; // maximum number of sides of a polygon (at most 6) ... System.out.print("Polygons with at most " + sides + " sides: "); switch (sides) { case 6: System.out.print("hexagon, "); case 5: System.out.print("pentagon, "); case 4: System.out.print("rectangle, "); case 3: System.out.println("triangle"); break; case 2: case 1: System.out.println("none"); break; default: System.out.println; °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 14 UNIT 5 System.out.println;("Please input a value <= 6."); } If the value of sides is equal to 5, then the preceding code prints: pentagon, rectangle, triangle Note: When we omit the break statements, the order in which the various cases are written becomes important. This can easily cause errors. Hence, it is a good programming practice to insert break as the last statement in each case. Exercises Exercise 5.1. Write a program that reads a real number and prints a message according to the following table: alcohol content g message 40 < g extra strong liquor 20 < g ≤ 40 strong liquor 15 < g ≤ 20 liquor 12 < g ≤ 15 strong vine 10.5 < g ≤ 12 normal vine g ≤ 10.5 light vine Exercise 5.2. Write a program that reads from input the lengths of the three sides of a triangle and determines the type of the triangle according to the following algorithm: compare each pair of sides and count home many pairs are equal if (the number of equal pairs is 0 ) it is irregular else if (the number of equal pairs is 1 ) it is symmetric else it is regular Exercise 5.3. Write a program that reads from input the lengths of the three sides of a triangle and determines the type of the triangle by using if-else statements with complex conditions. Exercise 5.4. Realize a Java class to represent triangles, on which the following functionalities are defined: • creation of a triangle, given the lenghts of the three sides; • return of the length of the longest side, the intermediate side, and the shortest side; • test whether the three sides can actually be the sides of a triangle; i.e., they respect the triangular inequality, which states that the longest side is shorter than the sum of the other two; • return of the perimeter of the triangle; • return of the area of the triangle; notice that, given the lengths a, b, and c of the three sides of a triangle, the area A can be computed according to A = p s · (s − a) · (s − b) · (s − c), where s = (a + b + c)/2 is the semiperimeter; • return of a string representing the type of the triangle, which may be either regular, symmetric, or irregular. Write also a program to test all functionalities of the class representing triangles. Exercise 5.5. Write a program that reads from input the coefficients a, b, c of the quadratic equation a · x 2 + b · x + c = 0 and computes the zeroes of the equation. Depending on the sign of the discriminant b 2 − 4 · a · c, the program should print the two distinct real solutions, the real double solution, or the two complex solutions. °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05 Conditional statements 15 Exercise 5.6. Write a program that reads from input a line of text containing a YES/NO question (without final question mark) and prints an answer to the question according to the following rules: 1. if the line starts with a vocal, the answer is "MAYBE". 2. if the last letter of the line is "a", "i", or "u", the answer is "YES"; 3. if the last letter of the line is "e" or "o", the answer is "NO"; 4. if the last letter of the line is a character different from "a", "e", "i", "o", "u", the answer is "DON'T KNOW"; Note: When two rules can be applied, the answer is obtained by concatenating the answers for the two rules. Exercise 5.7. Realize a Java class to represent dates, on which the following functionalities are defined: • creation of a date, given day, month, and year; • return of day, month, and year; • test whether two dates are equal; • test whether a date precedes another date; • test whether the year of a date is a leap year; • compute the date of the next day. Write also a program to test all functionalities of the class representing dates. °c Diego Calvanese Lecture Notes for Introduction to Programming A.A. 2004/05

How a class can be considered a "smart data type"

Rational Software Architect 8.5.x: new features and enhancements Be the first to ask a question Product documentation Abstract This document provides an overview of new features and enhancments in IBM Rational Software Architect version 8.5 releases. Content Tab navigation 9.0 Release 8.5.5 Fix Pack 4 8.5.5 Fix Pack 3 8.5.5 Fix Pack 2 8.5.5 Fix Pack 1 8.5 Fix Pack 5 8.5 Mod Pack 1 8.5. Release Rational Software Architect, Version 8.5.5.4 Link Date Released Status Download 8.5.5.4 Release 11/20/2015 Current This release of Rational Software Architect contains new features and enhancements in the following areas: IBM product integration support IBM Runtime Environment Java Technology Edition updates Eclipse platform updates Product integration support The following product integration is supported beginning with v8.5.5.4: Rational Common Licensing 8.1.4.8 IBM Installation Manager 1.8.3 Rational Team Concert 5.0.2 and 6.0 Back to top IBM Runtime Environment Java Technology Edition updates IBM Runtime Environment Java Technology Edition is updated to the following versions: IBM 32/64-bit Runtime Environment for Windows, Java Technology Edition, Version 7.0 Service Release 9 FP10 IBM 32/64-bit Runtime Environment for Linux, Java Technology Edition, Version 7.0 Service Release 9 FP10 Back to top Eclipse platform updates The following additional Eclipse 3.6.2.8 patches and fixes are included in this release: Eclipse platform: Bugzilla fixes 311192, 325743, 356184, 359931, 370864, 372273, 383790, 383796, 386472, 390368, 401992, 405942, 415061, 415065 Eclipse Data Tools: Bugzilla fixes 280268, 285515, 285524, 285542, 285803, 286895, 341329, 342411, 344445, 345677, 349889, 353797, 354040, 355859, 356865, 357576, 359486, 360896, 361034, 368412, 369352, 376454, 384194, 386944, 387430, 399992 Eclipse Equinox Core: Bugzilla fixes 359862, 374300 Eclipse Equinox p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Equinox Server: Bugzilla fixes 359862, 374300 Eclipse Equinox Server p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Java Development Tools (JDT): Bugzilla fixes 185601, 372687, 376734, 381172, 394718, 380927, 380750, 410207, 431275 Eclipse C/C++ Development Tooling (CDT) platform: Bugzilla fixes 338082, 338936, 344646, 346349, 347363, 347492, 350587, 351255, 352679, 352758, 352775, 353113, 354042, 354451, 354777, 355399, 356523, 370762, 372899, 372675, 379492 Eclipse C/C++ Development Tooling (CDT) LR Parser: Bugzilla fixes 366273, 378189, 388243 Eclipse C/C++ Development Tooling (CDT) Debug: Bugzilla fixes 363688, 386600, 397798 Eclipse C/C++ Development Tooling (CDT) XL Compiler (XLC): Bugzilla fixes 350501, 351255, 352758, 353113, 366273, 378270, 378578, 379474 Eclipse Concurrent Versions System (CVS): Bugzilla fix 361928 Eclipse Graphical Modeling Framework (GMF): Bugzilla fixes 359582, 376793, 412041, 422445 Eclipse Help: Bugzilla fix 375751 Eclipse Plug-in Development Environment (PDE): Bugzilla fix 389192 Eclipse Remote System Explorer (RSE) Core: Bugzilla fixes 333593, 334839, 340069, 340212, 346358, 348778, 348588, 350582, 353434, 353827, 354876, 355529, 355530, 355531, 357961, 358932, 359566, 359860, 367506, 368768, 370885, 373105, 372972, 372977, 375361, 375423, 376094, 376118, 376412, 377129, 377646, 377695, 378163, 379456, 379564, 379838, 380704, 385426, 385776, 386505, 388364, 388947, 390703, 391133, 398988, 399083, 402533, 406592, 409851, 425790, 427307, 435416, 459262 Eclipse Remote System Explorer (RSE) DStore: Bugzilla fixes 267478, 333593, 340432, 344884, 347445, 350582, 356231, 367506, 370885, 372972, 375423, 376094, 376118, 376412, 377646, 377695, 378163, 372977, 375361, 379456, 380562, 385794, 385097, 385873, 387323, 389289, 386311, 388875, 390039, 385196, 388527, 390456, 391067, 391166, 392014, 405309, 427307, 436716, 451409 Eclipse Remote System Explorer (RSE) FTP: Bugzilla fix 398988 Eclipse Remote System Explorer (RSE) Local Projects: Bugzilla fixes 337612, 395981, 422508, 422508, 427307 Eclipse Rich Client Platform (RCP): Bugzilla fixes 323431, 325743, 326311, 359862, 372273, 374300, 395464, 395642, 413625, 407043 Web Tools Platform (WTP) patches: Bugzilla 436412, 431752 Back to top Rational Software Architect, Version 8.5.5.3 Link Date Released Status Download 8.5.5.3 Release 10/04/2014 Superseded This release of Rational Software Architect contains new features and enhancements in the following areas: IBM product integration support IBM Runtime Environment Java Technology Edition updates Eclipse platform updates Product integration support The following product integration is supported beginning with v8.5.5.3: Rational Common Licensing 8.1.4.5 Rational Team Concert 5.0.2 Back to top IBM Runtime Environment Java Technology Edition updates IBM Runtime Environment Java Technology Edition is updated to the following versions: IBM 32-bit Runtime Environment for Windows, Java Technology Edition, Version 7.0 Service Release 8 FP10 BM 32-bit Runtime Environment for Linux, Java Technology Edition, Version 7.0 Service Release 8 FP10 Back to top Eclipse platform updates The following additional Eclipse 3.6.2.8 patches and fixes are included in this release: Eclipse platform: Bugzilla fixes 311192, 325743, 356184, 359931, 370864, 372273, 383790, 383796, 386472, 390368, 401992, 405942, 415061, 415065 Eclipse Data Tools: Bugzilla fixes 280268, 285515, 285524, 285542, 285803, 286895, 341329, 342411, 344445, 345677, 349889, 353797, 354040, 355859, 356865, 357576, 359486, 360896, 361034, 368412, 369352, 376454, 384194, 386944, 387430, 399992 Eclipse Equinox Core: Bugzilla fixes 359862, 374300 Eclipse Equinox p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Equinox Server: Bugzilla fixes 359862, 374300 Eclipse Equinox Server p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Java Development Tools (JDT): Bugzilla fixes 185601, 372687, 376734, 381172, 394718, 380927, 380750, 410207, 431275 Eclipse C/C++ Development Tooling (CDT) platform: Bugzilla fixes 338082, 338936, 344646, 346349, 347363, 347492, 350587, 351255, 352679, 352758, 352775, 353113, 354042, 354451, 354777, 355399, 356523, 370762, 372899, 372675, 379492 Eclipse C/C++ Development Tooling (CDT) LR Parser: Bugzilla fixes 366273, 378189, 388243 Eclipse C/C++ Development Tooling (CDT) Debug: Bugzilla fixes 363688, 386600, 397798 Eclipse C/C++ Development Tooling (CDT) XL Compiler (XLC): Bugzilla fixes 350501, 351255, 352758, 353113, 366273, 378270, 378578, 379474 Eclipse Concurrent Versions System (CVS): Bugzilla fix 361928 Eclipse Graphical Modeling Framework (GMF): Bugzilla fixes 359582, 376793, 412041, 422445 Eclipse Help: Bugzilla fix 375751 Eclipse Plug-in Development Environment (PDE): Bugzilla fix 389192 Eclipse Remote System Explorer (RSE) Core: Bugzilla fixes 333593, 334839, 340069, 340212, 346358, 348778, 348588, 350582, 353434, 353827, 354876, 355529, 355530, 355531, 357961, 358932, 359566, 359860, 367506, 368768, 370885, 373105, 372972, 372977, 375361, 375423, 376094, 376118, 376412, 377129, 377646, 377695, 378163, 379456, 379564, 379838, 380704, 385426, 385776, 386505, 388364, 388947, 390703, 391133, 398988, 399083, 402533, 406592, 409851, 425790, 427307, 435416, 459262 Eclipse Remote System Explorer (RSE) DStore: Bugzilla fixes 267478, 333593, 340432, 344884, 347445, 350582, 356231, 367506, 370885, 372972, 375423, 376094, 376118, 376412, 377646, 377695, 378163, 372977, 375361, 379456, 380562, 385794, 385097, 385873, 387323, 389289, 386311, 388875, 390039, 385196, 388527, 390456, 391067, 391166, 392014, 405309, 427307, 436716, 451409 Eclipse Remote System Explorer (RSE) FTP: Bugzilla fix 398988 Eclipse Remote System Explorer (RSE) Local Projects: Bugzilla fixes 337612, 395981, 422508, 422508, 427307 Eclipse Rich Client Platform (RCP): Bugzilla fixes 323431, 325743, 326311, 359862, 372273, 374300, 395464, 395642, 413625, 407043 Web Tools Platform (WTP) patches: Bugzilla 436412, 431752 Back to top Rational Software Architect, Version 8.5.5.2 Link Date Released Status Download 8.5.5.2 Release 26/09/2014 Superseded This release of Rational Software Architect contains new features and enhancements in the following areas: IBM Runtime Environment Java Technology Edition updates Eclipse platform updates IBM Runtime Environment Java Technology Edition updates Beginning with version 8.5.5.2, IBM SDK for Java Technology Edition is updated to the following versions: IBM 32-bit IBM SDK for Java Technology Edition for Windows, Version 7.0 Service Release 7 FP1 IBM 32-bit IBM SDK for Java Technology Edition for Linux, Version 7.0 Service Release 7 FP1 Back to top Eclipse platform updates The following additional Eclipse 3.6.2.7 patches and fixes are included in this release: Eclipse platform: Bugzilla fixes 311192, 325743, 356184, 359931, 370864, 372273, 383790, 383796, 386472, 390368, 401992, 405942, 415061, 415065 Eclipse Data Tools: Bugzilla fixes 280268, 285515, 285524, 285542, 285803, 286895, 341329, 342411, 344445, 345677, 349889, 353797, 354040, 355859, 356865, 357576, 359486, 360896, 361034, 368412, 369352, 376454, 384194, 386944, 387430, 399992 Eclipse Equinox Core: Bugzilla fixes 359862, 374300 Eclipse Equinox p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Equinox Server: Bugzilla fixes 359862, 374300 Eclipse Equinox Server p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Java Development Tools (JDT): Bugzilla fixes 185601, 372687, 376734, 381172, 394718, 380927, 380750, 410207, 431275 Eclipse C/C++ Development Tooling (CDT) platform: Bugzilla fixes 338082, 338936, 344646, 346349, 347363, 347492, 350587, 351255, 352679, 352758, 352775, 353113, 354042, 354451, 354777, 355399, 356523, 370762, 372899, 372675, 379492 Eclipse C/C++ Development Tooling (CDT) LR Parser: Bugzilla fixes 366273, 378189, 388243 Eclipse C/C++ Development Tooling (CDT) Debug: Bugzilla fixes 363688, 386600, 397798 Eclipse C/C++ Development Tooling (CDT) XL Compiler (XLC): Bugzilla fixes 350501, 351255, 352758, 353113, 366273, 378270, 378578, 379474 Eclipse Concurrent Versions System (CVS): Bugzilla fix 361928 Eclipse Graphical Modeling Framework (GMF): Bugzilla fixes 359582, 376793, 412041, 422445 Eclipse Help: Bugzilla fix 375751 Eclipse Plug-in Development Environment (PDE): Bugzilla fix 389192 Eclipse Remote System Explorer (RSE) Core: Bugzilla fixes 333593, 334839, 340069, 340212, 346358, 348778, 348588, 350582, 353434, 353827, 354876, 355529, 355530, 355531, 357961, 358932, 359566, 359860, 367506, 368768, 370885, 373105, 372972, 372977, 375361, 375423, 376094, 376118, 376412, 377129, 377646, 377695, 378163, 379456, 379564, 379838, 380704, 385426, 385776, 386505, 388364, 388947, 390703, 391133, 398988, 399083, 402533, 406592, 409851, 425790, 435416 Eclipse Remote System Explorer (RSE) DStore: Bugzilla fixes 267478, 333593, 340432, 344884, 347445, 350582, 356231, 367506, 370885, 372972, 375423, 376094, 376118, 376412, 377646, 377695, 378163, 372977, 375361, 379456, 380562, 385794, 385097, 385873, 387323, 389289, 386311, 388875, 390039, 385196, 388527, 390456, 391067, 391166, 392014, 405309, 436716 Eclipse Remote System Explorer (RSE) FTP: Bugzilla fix 398988 Eclipse Remote System Explorer (RSE) Local Projects: Bugzilla fixes 337612, 395981, 422508 Eclipse Rich Client Platform (RCP): Bugzilla fixes 323431, 325743, 326311, 359862, 372273, 374300, 395464, 395642, 413625 Web Tools Platform (WTP) patches: Bugzilla 436412, 431752 Back to top This release of Rational Software Architect contains new features and enhancements in the following areas: IBM product integration support IBM Runtime Environment Java Technology Edition Deployment planning IBM product integration support Beginning with version 8.5.5.1, the following products are supported for integration: Rational Common Licensing 8.1.4.2 Back to top IBM Runtime Environment Java Technology Edition updates Beginning with version 8.5.5.1, IBM SDK for Java Technology Edition is updated to the following versions: IBM 32-bit IBM SDK for Java Technology Edition for Windows, Version 7.0 Service Release 6 FP1 IBM 32-bit IBM SDK for Java Technology Edition for Linux, Version 7.0 Service Release 6 FP1 Back to top Deployment planning With the enhancements in the WebSphere Message Queue domain capabilities, you now can capture more information in the existing units such as MQQueueManager, MQQueue, MQChannel, etc. while creating deployment plans. WebSphere Message Queue domain deployment planning capabilities are now enhanced to model WMQ elements such as coupling facility structure, buffer pool, maximum shared messages, storage classes, etc. Security domain related units and templates are now supported for the creation of deployment plans corresponding to WebSphere Message Queue security components. Back to top Rational Software Architect, Version 8.5.5 Link Date Released Status Download 8.5.5 Release 13/09/2013 Superseded This release of Rational Software Architect contains new features and enhancements in the following areas: IBM product integration support IBM Runtime Environment Java Technology Edition Eclipse platform updates BPMN modeling Deployment planning Headless build tools IBM Assembly and Deploy Tools support IBM Build Utility support IBM Cloud Tools support IBM Integrated Test Environment Extension support Java EE Connector (J2C) tools Page Designer SCA tools UML modeler Web services tools WSDL and XSD transformations WSDL modeling and transformations IBM product integration support Beginning with version 8.5.5, the following products are supported for integration: IBM Installation Manager v1.6.3.1 Rational Common Licensing 8.1.3.3 Back to top IBM Runtime Environment Java Technology Edition updates IBM Runtime Environment Java Technology Edition is updated to the following versions: IBM 32-bit Runtime Environment for Windows, Java Technology Edition, Version 7.0 Service Release 5 IBM 32-bit Runtime Environment for Linux, Java Technology Edition, Version 7.0 Service Release 5 Back to top Eclipse platform updates The following additional Eclipse 3.6.2.5 patches and fixes are included in this release: Eclipse platform: Bugzilla fixes 311192, 325743, 356184, 359931, 370864, 372273, 383790, 383796, 386472, 390368 Eclipse Data Tools: Bugzilla fixes 280268, 285515, 285524, 285803, 286895, 341329, 342411, 344445, 349889, 353797, 354040, 355859, 356865, 357576, 359486, 360896, 361034, 368412, 369352, 376454, 384194, 387430 Eclipse Equinox Core: Bugzilla fixes 359862, 374300 Eclipse Equinox p2: Bugzilla fixes 348366, 363963, 363964, 398896 Eclipse Java Development Tools (JDT): Bugzilla fixes 185601, 372687, 376734, 380750, 380927, 381172, 394718, 403014 Eclipse C/C++ Development Tooling (CDT) LR Parser: Bugzilla fixes 366273, 378189, 388243 Eclipse C/C++ Development Tooling (CDT) Debug: Bugzilla fixes 363688, 386600, 397798 Eclipse Plug-in Development Environment (PDE): Bugzilla fix 389192 Eclipse Remote System Explorer (RSE) Core: Bugzilla fixes 333593, 334839, 340069, 340212, 346358, 348588, 348778, 350582, 353434, 353827, 354876, 355529, 355530, 355531, 357961, 358932, 359566, 359860, 367506, 368768, 370885, 372972, 372977, 373105, 375361, 375423, 376094, 376118, 376412, 377129, 377646, 377695, 378163, 379456, 379564, 379838, 380704, 385426, 385776, 386505, 388364, 388947, 390703, 391133, 398988, 402533 Eclipse Remote System Explorer (RSE) DStore: Bugzilla fixes 267478, 333593, 340432, 344884, 347445, 350582, 356231, 367506, 370885, 372972, 372977, 375361, 375423, 376094, 376118, 376412, 377646, 377695, 378163, 379456, 380562, 385097, 385196, 385794, 385873, 386311, 387323, 388527, 388875, 389289, 390039, 390456, 391067, 391166, 392014, 405309 Eclipse Remote System Explorer (RSE) FTP: Bugzilla fix 398988 Eclipse Remote System Explorer (RSE) Local Projects: Bugzilla fixes 337612, 395981 Eclipse Rich Client Platform (RCP): Bugzilla fixes 323431, 325743, 326311, 359862, 372273, 374300, 395464, 395642 Web Tools Platform (WTP) patches: Bugzilla fixes 404091, 407551, 410843, 410844, 413352, 414225 Back to top BPMN modeling You can now link collaboration and choreography models. You can reference the participants and message flows of collaboration models in choreography tasks through the Properties view and dialog boxes when creating choreography tasks. Back to top Deployment planning Deployment planning in v8.5.1 and earlier supports the basic modeling of IBM WebSphere MQ and IBM WebSphere Message Broker deployments. Now, the deployment planning capability for these domains are enhanced, and you can now model with more details. By default, you can use the IBM Tivoli Application Dependency Discovery Manager (TADDM) import feature to import pre-defined content from IBM Tivoli Change and Configuration Management Database (CCMDB). Now, you can contribute custom mappings and filters to the TADDM import functionality. You can also override the default mappings. Back to top Headless build tools You can now add an Ant task for the creation of a Rational Team Concert repository connection. Back to top IBM Assembly and Deploy Tools support IBM Assembly and Deploy Tools for WebSphere Administration is updated to 8.5.5 version. Back to top IBM Build Utility support IBM Rational Application Developer for WebSphere Software Build Utility is updated to 8.5.5 version. Back to top IBM Cloud Tools support IBM Rational Desktop Connection Toolkit for IBM Cloud Environments is updated to 1.0.5.3 version. Back to top IBM Integrated Test Environment Extension support IBM Intergrated Test Environment Extension support is updated for the IBM WebSphere Application Server, version 7.0.0.29, 8.0.07 and 8.5.5. Back to top Java EE Connector (J2C) tools CICS v8.1.0.2 resource adapter IMS v12.1.2 and and v11.3.3 resource adapter Back to top Page Designer You can now use "The same as template's links (unchanged)" option located at Window > Preferences > Web > Page Template > Links for a page, and apply "Default Link path when design-time" group template. When you apply a design-time template to a web page, the link path contributed by the template are as follows: Relative to document root directory Relative to document directory The same as template's links (unchanged) By selecting "The same as template's links (unchanged)" option, link paths from design-time templates are not modified in the web pages. Back to top SCA tools Web service over Java Message Service (JMS) is now supported by the SCA tools. In a service, you can now have attributes in a WebService binding that are accepted and validated. Back to top UML modeler The functionality of creating relationships between attributes of different classes has been improved. It leverages the node representation of attributes in the structure compartment of classes in class diagrams to create relationships between attributes. The improvements have been done in the following areas: You can now enable the structure compartment for all classes at the diagram level. The layout of attributes nodes can now be changed to vertical order. The default order is horizontal, but it can be customized from the Preferences window to ease the creation of relationships between attributes. Relationships between attributes in a diagram can now be re-established during drag/drop of elements, switching on/off the structure compartment views. You can now change the target and source of multiple messages concurrently in a sequence diagram. Back to top Web services tools The Web services wizard supports the creation of JAX-WS Web services and clients targeting IBM WebSphere Application Server Liberty. You can create JAX-WS Web services with the bottom-up and top-down approaches, and clients. You can create JAX-WS EJB Web services top-down. You can secure your web services and clients by using the new Web Service Security Policy for Liberty Server wizard. In this wizard, you can choose from a list of common policy 'templates' to apply policies to your web service. A new Deployment Descriptor Editor for the ibm-ws-bnd.xml files. This file allows you to override or customize settings and properties. The editor provides you with content assist and guided editing. Back to top WSDL and XSD transformations You can now control whether files, folders, or namespaces are renamed or not by using an option in the transformation configuration. Back to top WSDL modeling and transformations The WSDL modeling and transformations feature now supports editing of target namespaces and file names on the Output Options tab of the UML-to-WSDL transformation configuration window. With this, collation of multiple WSDL definitions and XSD schemas into a single WSDL file is now possible as is the collation of multiple XSD schemas into a single XSD file. Validation errors are thrown both on the table entries and on the transformation configuration validation if the collated WSDL definitions do not share the same target namespace. Back to top Rational Software Architect, Version 8.5.1 Link Date Released Status Download 8.5.1 Release 04/12/2012 Superseded This release of Rational Software Architect contains new features and enhancements in the following areas: Additional supported operating system versions IBM product integration support IBM Runtime Environment Java Technology Edition Eclipse platform updates Agent Controller updates Application build BPMN modeling Cloud toolkit Code coverage tools Compare and merge Deployment automation Developer tools support for creating applications by using Maven Hibernate modeling and transformations IBM Worklight support for REST services Java EE Connector (J2C) tools Java EE tools Java web services tools JSF tools Liberty Profile tools Microsoft Visio diagram import Performance tools Portal tools Project Explorer view REST modeling and JAXB transformations REST modeling and JAXRS transformations SCA tools Spring modeling and transformations UML-to-EJB 3.0 and UML-to-JPA transformations UML-to-JPA and UML-to-Hibernate transformations Web 2.0 and mobile tools Additional supported operating system versions Beginning with version 8..5.1, the following additional operating system versions are supported: Red Hat Enterprise Linux 5 Update 8 SUSE Linux Enterprise Server 11 Service Pack 2 SUSE Linux Enterprise Desktop 11 Service Pack 2 Ubuntu 12.04 LTS x32 & x64 Back to top IBM product integration support Beginning with version 8.5.1, the following products are supported for integration: IBM Installation Manager v1.6 Rational Common Licensing 8.1.3.1 Back to top IBM Runtime Environment Java Technology Edition updates IBM Runtime Environment Java Technology Edition is updated to the following versions: IBM 32-bit Runtime Environment for Windows, Java Technology Edition, Version 7.0 Service Release 2 IBM 32-bit Runtime Environment for Linux, Java Technology Edition, Version 7.0 Service Release 2 Back to top Eclipse platform updates The following additional Eclipse 3.6.2.4 patches and fixes are included in this release: Eclipse platform: Bugzilla fixes 311192, 325743, 356184, 359931, 370864, 372273, 383790, 383796, 386472, 390368 Eclipse Equinox p2: Bugzilla fixes 348366, 363963, 363964 Eclipse Java Development Tools (JDT): Bugzilla fixes 185601, 372687, 376734 Eclipse C/C++ Development Tooling (CDT) LR Parser: Bugzilla fixes 366273, 378189, 388243 Eclipse C/C++ Development Tooling (CDT) Debug: Bugzilla fixes 363688, 386600 Eclipse Data Tools: Bugzilla fixes 280268, 285515, 285524, 285542, 285803, 286895, 341329, 342411, 344445, 349889, 353797, 354040, 355859, 356865, 357576, 359486, 360896, 361034, 368412, 369352, 376454, 384194, 386944, 387430 Eclipse Plug-in Development Environment (PDE): Bugzilla fixes 389192, 393245 Remote System Explorer (RSE) Core: Bugzilla fixes 333593, 334839, 340069, 340212, 346358, 348588, 348778, 350582, 353434, 353827, 354876, 355529, 355530, 355531, 357961, 358932, 359566, 359860, 367506, 368768, 370885, 372972, 372977, 373105, 375361, 375423, 376094, 376118, 376412, 377129, 377646, 377695, 378163, 379456, 379564, 379838, 380704, 385426, 385776, 386505, 388364, 388947, 390703, 391133 Remote System Explorer (RSE) DStore: Bugzilla fixes 267478, 333593, 340432, 344884, 347445, 350582, 356231, 367506, 370885, 372972, 372977, 375361, 375423, 376094, 376118, 376412, 377646, 377695, 378163, 379456, 380562, 385097, 385196, 385794, 385873, 386311, 387323, 388527, 388875, 389289, 390039, 390456, 391067, 391166, 392014 Web Tools Platform (WTP) patches: Bugzilla fix 390993 Back to top Agent Controller updates Rational Agent Controller v8.3.6 Back to top Application build New Ant task <generateEJB3Stubs> for generating EJB 3 stubs had been added A <launchJUnit> task for generating JUnit reports has been enhanced to generate formatted reports of the test runs. Back to top BPMN modeling You can now create Multi-Instance markers for activities, pools, and choreography activities. The multi-instance characteristic properties of activities can be configured from the properties view. Also the multiple participant properties of pools and looptype characteristic of choreography activities can be configured from properties view. And the multi-instance characteristics can be exported to standard format file and imported from standard format file back into the product. You can now export BPMN project from the product to archive files outside the workspace and import of standard format BPMN files from archives back into the product. You can now create message flows to and from message events. Also the message flows can be exported to standard format and imported back into the product. Tags list in the exported page are now sorted. Tag page in the Export wizard has been enhanced with explanatory descriptions. Now in-place expansion of callactivities is supported. Callactivities can be expanded to show the details of the process it references and can be collapsed to hide the details. The export and import wizards are now more responsive (by making them asynch and have a progress indicator, which is cancelable): The wizard page has been consolidated and items have been regrouped for an optimal/usable experience. You will get a feedback at the end of the process if an export or import fails. Some usability improvements have been made (like history of last target, archive to be the default option, etc). Back to top Cloud toolkit Support for WebSphere Application Server, Version 8.5 is added. Back to top Code coverage tools Block coverage statistic is now measured in basic block, rather than based on the non-standard executable units (which more closely resemble source lines) as in previous releases. Back to top Compare and merge Ability to select one of the running instance of the product while performing compare merge. Improvement in dependency information in compare merge structural change pane to include dependency-supplier information. Improvement in trigger information in compare merge structural change pane to include related operation information. Addition of a new filter "Filter Out CompareMerge Induced Reference Modifications" to suppress compare merge induced reference changes. Text appearing in compare merge window of Transformation Configuration (TC) compare merge support showing the value field for a transformation property has been made as readable as possible so that it is comprehensible to the user. Earlier TC merge panes was displaying the text as it is as in the tc file which was not readable. It also provides extension point support that lets user provide display text for TC property IDs. It is now possible to exclude prerequisite TCs from being built. This can be accomplished by turning off TCs that are shown in the "Build transformation configurations" dialog box. Back to top Deployment automation When a topology is saved, persisting of the deployment model element's documentation without HTML tags is supported. The following new boolean preference option will be provided: Window > Preferences > Topology Editor > Enable rich text editor. By default, it is enabled. If this option is disabled, documentation of deployment model elements will be displayed by using a Plain text editor. When topology is saved, the documentation will be saved. Now you can adjust the order of the extended attributes by using the Customize attribute dialog box. New JET tag <deploy:extendedAttribute> is provided to support the following functionality: Search for the required extended attribute with matching name and type in the given owner capability. If matching extended attribute is present, update it. Otherwise create a new one. Deployment planning of IBM System p domain is supported. Deployment automation of the same is not supported. Deployment automation support for the IBM HTTP Server (IHS) domain is provided. Back to top Developer tools support for creating applications by using Maven Development support for Maven-based projects is added which provides a wizard to create new maven projects. This new feature can be optionally installed when you install IBM Rational Application Developer by using IBM Installation Manager. Existing Maven projects can be imported into the tools. The Maven POM can be edited using a form based editor. Maven repositories can be browsed to aid in the discovery of modules. Maven support can also be added to existing projects. Back to top Hibernate modeling and transformations Enhanced association support and joins. Added index modeling and transformation support for columns. Back to top IBM Worklight support for REST services IBM Worklight adapters are the server-side code of applications that are deployed on the IBM Worklight mobile application platform, and mediate between the mobile apps such as smartphones and tablets and the back-end services such as IBM WebSphere Application Server. You can generate IBM Worklight adapters codes and mobile clients stubs (that use the procedures that are provided by the adapters in a Worklight project) from a Representational State Transfer (REST) model or a Java API for RESTful Web Services (JAX-RS) model by running the UML-to-Worklight transformation. Back to top Java EE Connector (J2C) tools New CICS V8.1.0.1 resource adapter. New CICS Transaction Gateway for Multiplatforms V8.1.0.1. See the following pages for details of problems (APARS) fixed on Linux and Windows. New WebSphere 7.5.0.3 adapters. See the following page for details of problems fixed. Back to top Java EE tools Contexts and dependency injection The cdi-1.0 feature can be configured to enable initial support for the Contexts and Dependency Injection specification. The feature enables an expression language lookup of an @Named CDI style bean, with other CDI beans injected into it. The developer tools have been updated allow Context and Dependency Injection (CDI) support to be added to existing Java or JEE projects. When adding a CDI annotation to a POJO the developer tools provide a Quickfix to add WebSphere and Liberty profile support. The developer tools provide as-you-type validation for CDI specification rules. EJB lite The ejblite-3.1 feature can be configured to enable initial support for the EJB lite subset of the EJB specification. You can create @Stateless and @Singleton EJBs packaged in an EJB jar in an EAR file. The EJBs can then be injected into EJBs and Servlets using the @EJB annotation. Configuring the appSecurity-1.0 feature will allow the use of the @DenyAll, @DeclareRoles,@RunAs, @PermitAll, @RolesAllowed annotations. The developer tools have been updated to allow the deployment of applications containing EJBs to the Liberty profile, including adding the ejblite-3.1 feature to the runtime when the application is deployed. Back to top Java web services tools The jaxws-2.2 feature provides basic enablement of JAX-WS 2.2 specification for Web services. The support allows for annotated Web services and Web service references to be used within the web container. Stub clients and dynamic clients are both supported. Services may be POJO based, use Service Endpoint Interfaces, or be Provider based. Services may use automatically generated WSDL (bottom up) or may specify WSDL (top down). WSDL files are published to a URL of the service soap address concatenated with "?wsdl". Handler chains, resource injection, and MTOM attachments are also supported. Java API for XML Binding 2.2 The jaxb-2.2 feature can be configured to enable support for JAXB 2.2 specification. Back to top JSF tools New tooling added to support JCDI beans in JSF 2.0 projects: Named Beans category in the Paga Data view to content JCDI Named beans. EL auto-completion for JCDI Named beans, available in the source editor. A wizard option to add JCDI support from project creation. Back to top Liberty Profile tools Extending the Liberty profile You can expand the capability of the Liberty profile by using product extensions. Product extensions usually contain one or more features but can have any content that extends the liberty profile environment, for example scripts or resources. You can write your own Liberty features and install them into an existing Liberty profile server, or you can package them for delivery to your users. Implementing a function as a feature instead of as an application might be appropriate in a number of scenarios. The following list describes some of the benefits of using a feature: Features are controlled through feature manager configuration, so they are separate from user application management. Feature code has access to the liberty profile SPI, which allows deeper integration with the runtime environment. Features can receive user-specified configuration from the server.xml file, and expose their configuration settings in the development tools without the tools having to be changed. Features can easily expose classes and services to each other and to user applications. Features can be extremely lightweight with no application container dependencies. To write your own feature, create an OSGi bundle and a corresponding feature manifest, and place them into the required locations (the OSGi bundle goes in ${wlp.usr.dir}/extension/lib, and the feature manifest goes in ${wlp.user.dir}/extension/lib/features). The developer tools provide a wizard to create a Liberty feature and to easily add OSGi Bundles to it. A Subsystem Manifest Editor allows you to add OSGi bundles to the Liberty feature, declare API and SPI packages. Wizards allow the import and export of Liberty features as a zip file. Simplified server creation The server creation wizard has been simplified to reduce the time required to create an initial Liberty profile server. Server landing page Accessing the root page of the Liberty http endpoint now provides a basic introduction page to the Liberty profile. Developer friendly error page When running applications from a developer page the Liberty profile has always provided a different error page for application errors. This page has been updated to look like the landing page. Custom User Registries In addition to using the Basic, LDAP, and SAF registries you can now write and deploy custom user registries into the server. Custom User Registries are made available by defining an implementation of the com.ibm.websphere.security.UserRegistry class, packaging it in an OSGi bundle, and registering it as an OSGi service. The bundle is then engaged into the runtime using a Liberty feature. Generate Java dumps The server command can now be used to request a Java dump for a running server. The type of dump requested can be set using the --include option. Options are heap, system,and thread. For example, if you wanted all three of these, you would issue the command: server javadump --include=thread,system,heap The developer tools have been updated to allow the creation of a JVM dump as well as to expose all the normal server dump options. Note that not all dump report types are available on all Java Runtime Environments. Back to top Microsoft Visio diagram import UI Tooling support has been added as basic level capability to map Visio elements to UML elements (not attributes), and reuse them through a template-like mechanism. Back to top Performance tools Enhanced the WebSphere Application Server performance tuning annotation scan task to better identify which annotated resources can be safely filtered to improve publishing performance. Provides support to automatically fix performance tuning suggestions found by the WebSphere Application Server definition scan to improve server integration performance. Back to top Portal tools In business portlets, you can now use web-service interface in WebSphere Process Server instead of using the EJB APIs. Portlet palette items are now enabled for use with Rich Page Editor and available for drag and drop onto the portlet JSP. The Mobile Views wizard is enabled to allow in-line creation of multiple mobile views within portlets. Back to top Project Explorer view In the Project Explorer view, the ordering of elements did not consider the storage order for ordered meta features and there was no preference to control this behavior. With this Enhancement a new preference was provided to control this behavior. Find/Replace from the Project Explorer view now has a new scope "Enclosing Project". Back to top REST modeling and JAXB transformations You can now model the data as an XSD model. You can use UML-to-JAXB transformation to generate the JAXB classes from the model. JAXB-to-UML transformation is not supported as JAXB classes are mostly generated and not directly edited. Back to top REST modeling and JAXRS transformations JSON root wrapping is now support in REST modeling. The product now supports RootWrapping/Un-wrapping of JAXB classes for REST services. You can model a Custom Provider class called "Root Wrapper class". UML-to-JAXRS transformation generates this RootWrapping provider class which root-wraps/un-wraps the classes. By default the JSON serialization (of JAXB classes) will not root-wrap. Jackson, the JSON processor shipped with Websphere 8.0/8.5, doesn't support this either. Back to top SCA tools This release introduces improvements to facilitate SCA 1.1 (OASIS) development. These improvements include: Right-click actions added in the composite editor canvas: Create components, services, references. Set implementations and interfaces. Add bindings. Reflect implementation details for Java and Composite implementations into the component. Copy a WSDL URL of a published service that has Web Service binding. JMS binding properties editing updates: Configure Apache Tuscany's SCA 1.1 extensions. Configure IBM WebSphere Application Server's SCA 1.1 extensions. Additional updates: Deployment Assembly support for SCA 1.1 projects. New projects will have this support by default. For projects created in version 8.5, support can be added with the Add Deployment Assembly Support action in the context menu of the project. Create a deployment assembly layout. The layout can consist of a single jar, embedded jar and/or shared asset. Export an SCA 1.1 project by contribution or composite. Configure export preferences so that you can predefine options in the export wizard. EJB binding browse action: browse to a deployed remote EJB interface to let the tools configure the EJB binding URI. Back to top Spring modeling and transformations Modeling of Spring Web Flow 2.x is now supported. All the flows can be captured in a flow diagram. You can transform these models to target artifacts including the flow XML and related Java code. Reverse engineering is also supported to transform an existing application to a Spring Web Flow model. Back to top UML-to-EJB 3.0 and UML-to-JPA transformations The UML-to-EJB 3 and UML-to-JPA transformations now preserve the annotation and annotation attributes that cannot be modeled and hence not supported by the transformation. The transformation does not delete them when they are added to the generated code in the target project. Also the name and named native queries that are added to the generated code but not modeled are preserved and not deleted by the UML-to-JPA transformation. Back to top UML-to-JPA and UML-to-Hibernate transformations The new JPA Profile Basic and Hibernate Basic tabs is added for the attributes of the entity when modeling JPA and Hibernate entities respectively. The UI of JPA Profile and Hibernate tabs for entity and its attribute is improved but no change in the attributes supported. Back to top Web 2.0 and mobile jQuery Mobile Visual Editing Tools. jQuery Mobile widgets appear on the Palette for drag and drop generation. Additionally, the Properties View has been enhanced to provide editing capabilities for a number of jQuery Mobile elements. jQuery Plugin and Widget wizards to create custom jQuery plugins and widgets. This allows you to keep your custom jQuery code neatly organized into reusable modules. Enhancements to the Rich Page Editor Development Page with improved mobile device appearance in editor's Design pane. Rotation of the device layout in the design pane preview. Mode to scale the previewed contents. Support for jQuery Mobile Direct edit actions for many jQuery widget combinations as well as support for jQuery grids. jQuery Smart Highlight provides instant graphical feedback for jQuery selectors. Content assist is available for the jQuery API in the source editor. Back to top Rational Software Architect, Version 8.5 Link Date Released Status Download 8.5 Release 27/06/2012 Superseded This release of Rational Software Architect contains new features and enhancements in the following areas: IBM product integration support Updates to supported web browsers Eclipse platform updates Application build BPMN modeling Hibernate modeling and transformations J2SE domain modeling and Java transformations Microsoft Visio diagram import MQ domain modeling RAFW configuration discovery Rational RequisitePro integration Spring and Hibernate integration Spring annotation Spring Core modeling and transformations Spring MVC modeling Spring Transaction annotation Struts 2 modeling and transformations TADDM discovery UML modeler WebSphere Message Broker domain modeling Liberty Profile tools Server tools Web tools OSGi tools SCA tools Modern Batch tools Profiling tools Code coverage tools Portal tools XML tools Java web services tools JSF tools Performance tools Java EE Connector (J2C) tools IBM product integration support Beginning with version 8.5, the following products are supported for integration: IBM Rational Software Architect Design Manager, Version 3.0 IBM InfoSphere Data Architect, Version 8.1 Back to top Updates to to supported web browser Beginning with version 8.5, the following additional web browser versions are supported: Mozilla Firefox 8.0 and later Back to top Eclipse platform updates The following additional Eclipse 3.6.2.3 patches and fixes are included in this release: Eclipse platform: Bugzilla fixes 311192, 325743, 356184, 359931, 370864, 372273 Eclipse Equinox/Equinox server: Bugzilla fix 374300 Eclipse Equinox p2/Equinox server p2: Bugzilla fixes 363963, 363964 Eclipse Help: Bugzilla fix 375751 Eclipse Graphical Modeling Framework (GMF): Bugzilla fix 359582 Eclipse Java Development Tools (JDT): Bugzilla fix 372687 Eclipse Concurrent Versions System (CVS): Bugzilla fixes 130002, 361928 Eclipse C/C++ Development Tooling (CDT) platform/debug: Bugzilla fixes 338082, 338936, 344646, 346349, 347363, 347492, 350587, 351255, 352679, 352775, 352758, 353113, 354042, 354451, 354777, 355399, 356523, 370762, 372675, 372899, 379492 Eclipse C/C++ Development Tooling (CDT) LR Parser: Bugzilla fixes 366273, 378189 Eclipse C/C++ Development Tooling (CDT) XLC feature: Bugzilla fixes 130015, 350501, 351255, 352758, 353113, 366273, 378270, 378578, 379474 Eclipse Data Tools: Bugzilla fixes 280268, 285515, 285524, 285803, 286895, 341329, 342411, 349889, 354040, 356865, 368412, 369352, 280268, 285515, 285524, 285803, 286895, 341329, 342411, 349889, 354040, 356865, 345677, 344445, 359486, 360896, 361034, 280268, 285515, 285524, 285803, 286895, 341329, 342411, 349889, 354040, 356865, 344445, 359486, 360896, 361034, 280268, 285515, 285524, 285803, 286895, 341329, 342411, 349889, 354040, 356865 Remote System Explorer (RSE) core: Bugzilla fixes 129987, 129998, 130035 Remote System Explorer (RSE) DStore server: Bugzilla fixes 334839, 340069, 333593, 348778, 348588, 346358, 350582, 354876, 353434, 353827, 355529, 355530, 359860, 355531, 357961, 359566, 358932, 368768, 373105, 367506, 370885, 372972, 375423, 376094, 376118, 340212, 372977, 375361, 377129, 376412, 377646, 377695, 378163, 379456, 379564 Remote System Explorer (RSE) Local server: Bugzilla fix 337612 Rich Client Platform (RCP): Bugzilla fixes 325743, 372273, 374300 Web Tools Platform (WTP) patches: Bugzilla fixes 319219, 352850, 361280, 36128, 366903, 369587, 370891, 371828, 372524, 372766, 373025, 373563, 373658, 373663, 373666, 374531, 374535, 375660, 376096, 376202, 376220, 376255, 376262, 376345, 376502, 376654, 376658, 376747, 376996, 377095, 377533, 377566, 377578, 377677, 377835, 378160, 378503, 378905 Back to top Application build You can now import compressed .zip archives in headless mode. You can now create a WebSphere Application Server 8.5 runtime by using pluggable SDK for Java 6 and Java 7 support in headless mode. A new headless build sample is provided in the product for usage of modern functions and WebSphere Application Server 8.5. You can now model DB2 for zSeries infrastructure elements in a deployment topology. Back to top BPMN modeling Business Process Modeling Notation (BPMN) modeling now supports SubProcess. A SubProcess is an Activity whose internal details have been modeled using Activities, Gateways, Events, and Sequence Flows. A SubProcess is a graphical object within a Process, but it also can be opened to show a lower-level Process. Modeling support has been provided for Embedded SubProcess and AdHoc SubProcess. These elements can dragged and dropped from the Tool Palette, other elements can be added to them and the SubProcess can be expanded and collapsed to show or hide the details. The properties of AdHoc SubProcess can be edited from the Properties view. In addition, the SubProcess can be exported to a standard format and imported into the product. BPMN modeling now supports data association for events. Data objects, process data inputs, and data store can be connected to intermediate throw and end events to create data input associations. Start events and intermediate catch events can be connected to data objects, process data outputs, and data store to create data output associations. Also, the data associations can be exported to a standard format and imported into the product. BPMN modeling now supports tagging of BPMN elements, which are visible in the diagram. Comma separated list of tags can be entered for an element in properties view. The tags can be used in BPMN 2.0 Export wizard to filter the elements that gets exported. BPMN modeling now supports Black Box pools(pools without a process). Also support for adding message flows to/from boundary of pools has been added. BPMN modeling now supports adding usecase artifacts to a sub process from the properties view. BPMN modeling now supports adding assignments for data associations. The From and To assignment expressions for a data association can be edited from the properties view. Back to top Hibernate modeling and transformations Modeling and code generation for the Hibernate domain is now supported. Before you can use this feature, you must set up a Hibernate development environment. You can model hibernate elements, such as entity, entity from table, and inheritance. You can use the UML-to-Hibernate transformation to generate Java code that contains Hibernate annotations, and use the Hibernate-to-UML transformation to transform Java code that contains Hibernate annotations into UML models. Back to top J2SE domain modeling and Java transformations Java 7 is now supported in domain modeling and transformations. You can visualize Java 7 Language construts in static method sequence diagrams and generate Java 7 compatible code in forward and reverse transformations. Important: To work with this new feature, you must install JDK 1.7 separately and include it in the build path of your Java project. Back to top Microsoft Visio diagram import The product now facilitates importing some Microsoft Visio diagrams, including class, usecase, and network diagrams. It is a one-time import and is automated in nature. Class and usecase diagrams are imported as UML diagrams, while network diagrams are imported as topology diagrams. The import captures the visual and semantic model, i.e. both the diagram as well as the underlying semantics. It uses Sketcher elements, wherever there is no matching target element in the product. The product supports Visio 2010 and the file format required is Visio XML (*.vdx). Back to top MQ domain modeling The WebSphere MQ domain now includes support for clustered queue mangers, queues, additional configurations, and many other enhancements to align it with the Tivoli Common Data Model and the MQ product itself. Back to top RAFW configuration discovery Now you can import the Rational Automation Framework (RAF) discovered configuration files into a deployment topology. Also supported is the import of ND environments, such as nodes, cells, servers, deployment managers, etc. Back to top Rational RequisitePro integration You can now use the Requirement perspective to open projects from a remote Rational RequisitePro web (RequisiteWeb) server, removing the requirement of having the Rational RequisitePro client for Windows installed on your local computer. You must have one of the following fix packs for Rational RequisitePro installed on the RequisiteWeb server for this configuration: For version 7.1.1, use 7.1.1.8 or later For version 7.1.2, use 7.1.2.5 or later For version 7.1.3, use 7.1.3.1 or later Back to top Spring and Hibernate integration Profile and template model with Spring and Hibernate features have been added as part of this new functionality. You can use this template model for modeling Hibernate models, where you want to use Spring Core features as well. Back to top Spring annotation Modeling and code generation for Spring Core Annotations is now supported. Spring Annotations like Component, Configuration, Service, Bean, Autowired, Value, Required, and Qualifier have been added. However, custom Annotation with Qualifier and CustomAutowireConfigurer are not support yet. Annotations can be modeled through the class diagram Tool Palette and menu action, and details can be provided in the Properties view on the Spring tab. Transformation generates annotated Java classes. Back to top Spring Core modeling and transformations Modeling and code generation for the Spring Core domain is now supported. Before you can use this feature, you must set up a Spring development environment. You can model Spring Core beans and dependency injections by using class diagrams, and generate Spring configuration XML files by using the Spring transformation extension for Java transformations. You can also reverse engineer Spring projects: the Java-to-UML transformation, with the Spring transformation extension enabled, can identify Spring beans that are defined in XML files and create them in the generated model. Spring Core annotations are not currently supported. Back to top Spring MVC modeling Modeling and code generation for the Spring model-view-controller (MVC) domain is now supported. Before you can use this feature, you must set up a Spring development environment. Spring Core features are required to work with Spring MVC. Spring MVC elements like Controllers, handler mappings, interceptors, etc. can be modeled through a class diagram or an activity diagram, where the entire MVC flow can be modeled. Spring MVC artifacts along with Spring Core artifacts can be generated by using the Spring MVC transformation extension for Java transformations. You can also reverse engineer Spring MVC projects through the Java-to-UML transformation, with the Spring MVC transformation extension enabled. The Spring MVC transformation also generates the MVC flows for you by parsing the Spring xml files and annotated Java code. Back to top Spring Transaction annotation Modeling and code generation for Spring Transaction annotations has been added. Repository and Transactional features can be added in class diagrams through the Tool Palette and menu actions. Details can be provided in the Properties view on the Spring Txn tab. Transformation generates annotated Java classes. Back to top Struts 2 modeling and transformations Modeling and code generation for the Struts 2 domain is now supported. You can model Struts 2 navigation flows by using UML activity diagrams, and generate Struts 2 configuration XML files by using the Struts 2 transformation extension for Java transformations. You can also reverse engineer Struts 2 projects: the Java-to-UML transformation, with the Struts 2 transformation extension enabled, can identify navigation flows that are defined in XML files, and automatically generate activity diagrams. Back to top Structured data import Several new enhancements have been introduced in structured data import, including updated JET tags and the ability to use non-CSV files in the wizard. Back to top TADDM discovery Tivoli Application Dependency Discovery Manager (TADDM) discovery supports several enhancements, including the ability to discover MQ and Message Broker content. Back to top UML modeler The generation of UML class diagrams from UML models is now supported. A pop-up menu on a model or package for class diagram generation has been provided for generating UML diagrams based on Rational Software Analyzer UML model metric rules. You need to select rules based on which diagrams would be generated. The framework is extensible in the sense that you would be able to contribute your own customized rules and use the analysis result against that rule for diagram generation. All you need to do is to contribute and implement an interpreter for the rules through an extension point. The Inheritance Explorer now supports sorting member elements according to the inheritance order (so that inherited elements are shown before locally defined elements). The General tab of the Properties view now shows the qualified name of an element. Each name in the qualifier is a hyperlink that can be used for navigation. There is also a Copy button that places the qualified name in the clipboard. The transformation configuration editor now provides an action Show in Project Explorer from its pop-up header menu, that will locate the .tc file in the Project Explorer view. An action menu, Navigate > Navigate To Diagram, has been introduced. You can now navigate from a UML semantic element to it's view in diagram. If diagram is not open, the action will open the diagram where there is the view for the selected element, which is highlighted. If there happens to be more than one view for a given UML element, the search view is launched. It lists all the diagram references for the selected element within in the context of the enclosing model and the first reference from the search view is highlighted. You can double-click or right click and invoke the Select In Diagram action on any other references in the search view to navigate to those views in diagram. The diagram generation UI now provides the relationship types tree. You can select the relationships types that you want to see in the generated diagram with respect to the elements fetched by the rule. You can also choose to generate individual diagram for individual elements found by the selected rule. You can now perform incremental text searches on all UML elements in diagrams, except topic and browse diagrams. Back to top WebSphere Message Broker domain modeling You can now model WebSphere Message Broker elements in a deployment topology, including message brokers, execution groups, message flows, message flow nodes, and more. Back to top Liberty Profile tools WebSphere Application Server V8.5 Liberty Profile Support The WebSphere Application Server V8.5 Liberty Profile tools is a set of tools focusing on the needs of developers for rapid development and deployment. Lightweight and fast, these tools support the features of IBM WebSphere Application Server 8.5 - Liberty Profile. The tools also facilitate application development and deployment, runtime installation, and server configuration and management. The Liberty Profile tools accelerate and simplify your work by helping you to: Develop, test, and deploy Web applications, enterprise applications, OSGi applications quickly. You can run applications directly from your workspace regardless of how the project is structured. It automatically adds required features to the server by analyzing your applications, ensuring that your applications can be run successfully on the server. Debug application easily by clicking on linked error messages on your web pages that open the editor for your source files. Make common resources to be shared by different applications on the server. You can define, configure, and publish shared libraries for the common resources. Download, install and set up WebSphere Application Server V8.5 Liberty Profile seamlessly within the tools. Edit server configurations with the new Server Configuration Editor. The editor has various dialogs and content assist to guide you through setting up the server configuration. It contains validators to validate the correctness of the configuration, and quick fixes to help address any problems your configuration may have. Manage the WebSphere Application Server V8.5 Liberty Profile runtime with the new runtime explorer view. The runtime explorer view shows the servers defined on the runtimes, the shared resources, and the applications that are running on the server in a single view. It allows you to create new servers and runtimes, to delete existing servers and runtimes, and to include configuration files in you server configuration. Perform server tasks simply. From the server context menu, you can package the server, create SSL certificates for the server, and generate Web server plug-in for the server. Back to top Server tools WebSphere Application Server V8.5 support WebSphere Application Server V8.5 support is added for you to take advantage of the latest functionality provided by the WebSphere Application Server v8.5. You can develop, test, and debug applications running on WebSphere Application Server V8.5. Java 7 support for WebSphere Application Server V8.5 Java 7 support for WebSphere Application Server v8.5 applications is added for you to take advantage of the latest functionality provided by Java 7. You can switch between Java 7 and Java 6 support for WebSphere Application Server v8.5 runtime. Migration support is added to migrate projects targeted WebSphere Application Server v8.5 runtime with Java 7 to target WebSphere Application Server v8.5 runtime with Java 6. Ability to deactivate a WebSphere Application Server in the Servers view You can deactivate either a started or stopped WebSphere Application Server in the Servers view to reduce network traffic and memory consumption if you do not need to interact with the server for a long period of time. Back to top Web tools The Rich Page Editor can be used for Dojo Mobile Web Page editing and provides support for JSP and JSP fragment pages. Safari browser support on Windows was added. The Dojo libraries are optional in Rational Application Developer and Websphere Developer Tools, allowing the user to choose whether to install them which provides for greater control over disk footprint. The wizards for creating a static or dynamic web project have been replaced by a single wizard providing a user-friendly interface for creating various types of web projects. A web preview server replaces the Ajax test server providing improved publishing support and logging and error messages from running web projects. Functional and performance improvements were made to the JavaScript and Dojo Tools. Dojo 1.7 RC2 is included. Back to top OSGi tools Modular EJBs Full support of EJBs in OSGi Bundles, and OSGi applications. The ability to create new, or convert existing EJB modules into OSGi bundles The ability to create EJB Client bundles, during or after the creation of an EJB Bundle Deployment of the OSGi application containing EJB Bundles to WebSphere v8.5 Support for promoting EJB session beans as OSGi Services Support for EJB session beans in EJB or Web 3.x bundles. Deployment of OSGi applications to WebSphere Application Server v8.5, and WebSphere Liberty Profile v8.5 Integration of the OSGi programming model in the Web Project Wizard OSGi Programming model selection in the first page of the Web Project wizard. OSGi Deployment page in the wizard to add the generated web Bundle to an OSGi application Back to top SCA tools This release provides tools for the development of OASIS SCA v1.1 applications for WebSphere Application Server v8.5. For more information about OASIS SCA 1.1, see http://oasis-opencsa.org/sca. If you developed SCA applications with an earlier version of Rational Application Developer, then you will find the new OASIS SCA tools to be very similar to the existing OSOA SCA tools. You can install the existing SCA Tools, the new SCA 1.1 Tools or both. The following tools can be used to develop applications that conform to the OASIS SCA 1.1 assembly model: Wizards Graphical composite and contribution editors Deployment, testing and debugging on WebSphere Application Server v8.5 Java and XML editor content assist enhancements including support for OASIS SCA annotations. Validation rules for Java implementations and interfaces Generation of JAXB interfaces from a WSDL Preferences page Samples Rational Application Developer v8.5 and WebSphere Application Server v8.5 support the following OASIS SCA v1.1 specifications: Assembly spec v1.1 http://docs.oasis-open.org/opencsa/sca-assembly/sca-assembly-spec-v1.1.pdf JMS binding http://docs.oasis-open.org/opencsa/sca-bindings/sca-jmsbinding-1.1-spec.pdf WS binding http://docs.oasis-open.org/opencsa/sca-bindings/sca-wsbinding-1.1-spec.pdf EJB binding http://docs.oasis-open.org/opencsa/sca-j/sca-ejbbinding-1.1-spec.pdf Java component implementation http://docs.oasis-open.org/opencsa/sca-j/sca-javaci-1.1-spec.pdf Java common annotations and API http://docs.oasis-open.org/opencsa/sca-j/sca-javacaa-1.1-spec.pdf JAXB 2.0 http://jcp.org/aboutJava/communityprocess/final/jsr222/index.html SDO 2.1.1 http://jcp.org/aboutJava/communityprocess/final/jsr235/index.html Back to top Modern Batch tools The Modern Batch Tools, in addition to supporting the WebSphere Application Server Modern Batch Feature pack, now support targeting both WebSphere Application Server 8 augmented with WebSphere Compute Grid 8, and WebSphere Application Server 8.5 (with full WebSphere Compute Grid built in). The Modern Batch tools include additional enhancements, such as: Improved support for additional xJCL commands and elements. Improved validation and codegen options. Supporting mixed type Job's for more flexibility. Editor changes for new model elements. Support for Parallel jobs (run element). Listener types. Back to top Profiling tools Java 7 support for profiling You can now profile when running Java 7 applications. Profiling support for WebSphere Application Server v8.5 and WebSphere Application Server v8.5 Liberty Profile You can now profile applications running on WebSphere Application Server v8.5 and WebSphere Application Server v8.5 Liberty Profile using both Java 6 and Java 7. Note: For Java 7 support on a remote server, you must install Rational Agent Controller v8.3.5. Removed profiling support for the JVMPI profiler and for Java 1.4 applications Profiling support for the JVMPI profiler and for application running on a Java 1.4 JVM have now been removed. You can continue to use the JVMTI profiler which is supported for application running on Java 1.5 and newer JVMs. Back to top Code coverage tools Java 7 support for code coverage You can now gather code coverage statistic when running Java 7 applications. Code Coverage support for WebSphere Application Server v8.5 and WebSphere Application Server v8.5 Liberty Profile You can now collect code coverage statistic on applications running on onWebSphere Application Server v8.5 and WebSphere Application Server v8.5 Liberty Profile using both Java 6 and Java 7. Code coverage supported in Run and Debug mode for all servers When profiling on server, you will no longer be prompted to choose between different analysis types as "Code Coverage Analysis" had been removed from the Profile On Server wizard and the preference. By default, profile on server will now always perform "Java Analysis". Instead of selecting Profile on Server to collect code coverage statistics, you can now get code coverage analysis by

Our style conventions for naming program entities, including comments in our programs, and formatting our programs.

Google Python Style Guide 1 Background Python is the main dynamic language used at Google. This style guide is a list of dos and don'ts for Python programs. To help you format code correctly, we've created a settings file for Vim. For Emacs, the default settings should be fine. Many teams use the yapf auto-formatter to avoid arguing over formatting. 2 Python Language Rules 2.1 Lint Run pylint over your code. 2.1.1 Definition pylint is a tool for finding bugs and style problems in Python source code. It finds problems that are typically caught by a compiler for less dynamic languages like C and C++. Because of the dynamic nature of Python, some warnings may be incorrect; however, spurious warnings should be fairly infrequent. 2.1.2 Pros Catches easy-to-miss errors like typos, using-vars-before-assignment, etc. 2.1.3 Cons pylint isn't perfect. To take advantage of it, we'll need to sometimes: a) Write around it b) Suppress its warnings or c) Improve it. 2.1.4 Decision Make sure you run pylint on your code. Suppress warnings if they are inappropriate so that other issues are not hidden. To suppress warnings, you can set a line-level comment: dict = 'something awful' # Bad Idea... pylint: disable=redefined-builtin pylint warnings are each identified by symbolic name (empty-docstring) Google-specific warnings start with g-. If the reason for the suppression is not clear from the symbolic name, add an explanation. Suppressing in this way has the advantage that we can easily search for suppressions and revisit them. You can get a list of pylint warnings by doing: pylint --list-msgs To get more information on a particular message, use: pylint --help-msg=C6409 Prefer pylint: disable to the deprecated older form pylint: disable-msg. Unused argument warnings can be suppressed by deleting the variables at the beginning of the function. Always include a comment explaining why you are deleting it. "Unused." is sufficient. For example: def viking_cafe_order(spam, beans, eggs=None): del beans, eggs # Unused by vikings. return spam + spam + spam Other common forms of suppressing this warning include using '_' as the identifier for the unused argument, prefixing the argument name with 'unused_', or assigning them to '_'. These forms are allowed but no longer encouraged. The first two break callers that pass arguments by name, while the last does not enforce that the arguments are actually unused. 2.2 Imports Use import statements for packages and modules only, not for individual classes or functions. Note that there is an explicit exemption for imports from the typing module. 2.2.1 Definition Reusability mechanism for sharing code from one module to another. 2.2.2 Pros The namespace management convention is simple. The source of each identifier is indicated in a consistent way; x.Obj says that object Obj is defined in module x. 2.2.3 Cons Module names can still collide. Some module names are inconveniently long. 2.2.4 Decision Use import x for importing packages and modules. Use from x import y where x is the package prefix and y is the module name with no prefix. Use from x import y as z if two modules named y are to be imported or if y is an inconveniently long name. Use import y as z only when z is a standard abbreviation (e.g., np for numpy). For example the module sound.effects.echo may be imported as follows: from sound.effects import echo ... echo.EchoFilter(input, output, delay=0.7, atten=4) Do not use relative names in imports. Even if the module is in the same package, use the full package name. This helps prevent unintentionally importing a package twice. Imports from the typing module are exempt from this rule. 2.3 Packages Import each module using the full pathname location of the module. 2.3.1 Pros Avoids conflicts in module names or incorrect imports due to the module search path not being what the author expected. Makes it easier to find modules. 2.3.2 Cons Makes it harder to deploy code because you have to replicate the package hierarchy. Not really a problem with modern deployment mechanisms. 2.3.3 Decision All new code should import each module by its full package name. Imports should be as follows: Yes: # Reference absl.flags in code with the complete name (verbose). import absl.flags from doctor.who import jodie FLAGS = absl.flags.FLAGS # Reference flags in code with just the module name (common). from absl import flags from doctor.who import jodie FLAGS = flags.FLAGS No: (assume this file lives in doctor/who/ where jodie.py also exists) # Unclear what module the author wanted and what will be imported. The actual # import behavior depends on external factors controlling sys.path. # Which possible jodie module did the author intend to import? import jodie The directory the main binary is located in should not be assumed to be in sys.path despite that happening in some environments. This being the case, code should assume that import jodie refers to a third party or top level package named jodie, not a local jodie.py. 2.4 Exceptions Exceptions are allowed but must be used carefully. 2.4.1 Definition Exceptions are a means of breaking out of the normal flow of control of a code block to handle errors or other exceptional conditions. 2.4.2 Pros The control flow of normal operation code is not cluttered by error-handling code. It also allows the control flow to skip multiple frames when a certain condition occurs, e.g., returning from N nested functions in one step instead of having to carry-through error codes. 2.4.3 Cons May cause the control flow to be confusing. Easy to miss error cases when making library calls. 2.4.4 Decision Exceptions must follow certain conditions: Raise exceptions like this: raise MyError('Error message') or raise MyError(). Do not use the two-argument form (raise MyError, 'Error message'). Make use of built-in exception classes when it makes sense. For example, raise a ValueError if you were passed a negative number but were expecting a positive one. Do not use assert statements for validating argument values of a public API. assert is used to ensure internal correctness, not to enforce correct usage nor to indicate that some unexpected event occurred. If an exception is desired in the latter cases, use a raise statement. For example: Yes: def connect_to_next_port(self, minimum): """Connects to the next available port. Args: minimum: A port value greater or equal to 1024. Raises: ValueError: If the minimum port specified is less than 1024. ConnectionError: If no available port is found. Returns: The new minimum port. """ if minimum < 1024: raise ValueError('Minimum port must be at least 1024, not %d.' % (minimum,)) port = self._find_next_open_port(minimum) if not port: raise ConnectionError('Could not connect to service on %d or higher.' % (minimum,)) assert port >= minimum, 'Unexpected port %d when minimum was %d.' % (port, minimum) return port No: def connect_to_next_port(self, minimum): """Connects to the next available port. Args: minimum: A port value greater or equal to 1024. Returns: The new minimum port. """ assert minimum >= 1024, 'Minimum port must be at least 1024.' port = self._find_next_open_port(minimum) assert port is not None return port Libraries or packages may define their own exceptions. When doing so they must inherit from an existing exception class. Exception names should end in Error and should not introduce stutter (foo.FooError). Never use catch-all except: statements, or catch Exception or StandardError, unless you are re-raising the exception or in the outermost block in your thread (and printing an error message). Python is very tolerant in this regard and except: will really catch everything including misspelled names, sys.exit() calls, Ctrl+C interrupts, unittest failures and all kinds of other exceptions that you simply don't want to catch. Minimize the amount of code in a try/except block. The larger the body of the try, the more likely that an exception will be raised by a line of code that you didn't expect to raise an exception. In those cases, the try/except block hides a real error. Use the finally clause to execute code whether or not an exception is raised in the try block. This is often useful for cleanup, i.e., closing a file. When capturing an exception, use as rather than a comma. For example: try: raise Error() except Error as error: pass 2.5 Global variables Avoid global variables. 2.5.1 Definition Variables that are declared at the module level or as class attributes. 2.5.2 Pros Occasionally useful. 2.5.3 Cons Has the potential to change module behavior during the import, because assignments to global variables are done when the module is first imported. 2.5.4 Decision Avoid global variables. While they are technically variables, module-level constants are permitted and encouraged. For example: MAX_HOLY_HANDGRENADE_COUNT = 3. Constants must be named using all caps with underscores. See Naming below. If needed, globals should be declared at the module level and made internal to the module by prepending an _ to the name. External access must be done through public module-level functions. See Naming below. 2.6 Nested/Local/Inner Classes and Functions Nested local functions or classes are fine when used to close over a local variable. Inner classes are fine. 2.6.1 Definition A class can be defined inside of a method, function, or class. A function can be defined inside a method or function. Nested functions have read-only access to variables defined in enclosing scopes. 2.6.2 Pros Allows definition of utility classes and functions that are only used inside of a very limited scope. Very ADT-y. Commonly used for implementing decorators. 2.6.3 Cons Instances of nested or local classes cannot be pickled. Nested functions and classes cannot be directly tested. Nesting can make your outer function longer and less readable. 2.6.4 Decision They are fine with some caveats. Avoid nested functions or classes except when closing over a local value. Do not nest a function just to hide it from users of a module. Instead, prefix its name with an _ at the module level so that it can still be accessed by tests. 2.7 Comprehensions & Generator Expressions Okay to use for simple cases. 2.7.1 Definition List, Dict, and Set comprehensions as well as generator expressions provide a concise and efficient way to create container types and iterators without resorting to the use of traditional loops, map(), filter(), or lambda. 2.7.2 Pros Simple comprehensions can be clearer and simpler than other dict, list, or set creation techniques. Generator expressions can be very efficient, since they avoid the creation of a list entirely. 2.7.3 Cons Complicated comprehensions or generator expressions can be hard to read. 2.7.4 Decision Okay to use for simple cases. Each portion must fit on one line: mapping expression, for clause, filter expression. Multiple for clauses or filter expressions are not permitted. Use loops instead when things get more complicated. Yes: result = [mapping_expr for value in iterable if filter_expr] result = [{'key': value} for value in iterable if a_long_filter_expression(value)] result = [complicated_transform(x) for x in iterable if predicate(x)] descriptive_name = [ transform({'key': key, 'value': value}, color='black') for key, value in generate_iterable(some_input) if complicated_condition_is_met(key, value) ] result = [] for x in range(10): for y in range(5): if x * y > 10: result.append((x, y)) return {x: complicated_transform(x) for x in long_generator_function(parameter) if x is not None} squares_generator = (x**2 for x in range(10)) unique_names = {user.name for user in users if user is not None} eat(jelly_bean for jelly_bean in jelly_beans if jelly_bean.color == 'black') No: result = [complicated_transform( x, some_argument=x+1) for x in iterable if predicate(x)] result = [(x, y) for x in range(10) for y in range(5) if x * y > 10] return ((x, y, z) for x in xrange(5) for y in xrange(5) if x != y for z in xrange(5) if y != z) 2.8 Default Iterators and Operators Use default iterators and operators for types that support them, like lists, dictionaries, and files. 2.8.1 Definition Container types, like dictionaries and lists, define default iterators and membership test operators ("in" and "not in"). 2.8.2 Pros The default iterators and operators are simple and efficient. They express the operation directly, without extra method calls. A function that uses default operators is generic. It can be used with any type that supports the operation. 2.8.3 Cons You can't tell the type of objects by reading the method names (e.g. has_key() means a dictionary). This is also an advantage. 2.8.4 Decision Use default iterators and operators for types that support them, like lists, dictionaries, and files. The built-in types define iterator methods, too. Prefer these methods to methods that return lists, except that you should not mutate a container while iterating over it. Never use Python 2 specific iteration methods such as dict.iter*() unless necessary. Yes: for key in adict: ... if key not in adict: ... if obj in alist: ... for line in afile: ... for k, v in adict.items(): ... for k, v in six.iteritems(adict): ... No: for key in adict.keys(): ... if not adict.has_key(key): ... for line in afile.readlines(): ... for k, v in dict.iteritems(): ... 2.9 Generators Use generators as needed. 2.9.1 Definition A generator function returns an iterator that yields a value each time it executes a yield statement. After it yields a value, the runtime state of the generator function is suspended until the next value is needed. 2.9.2 Pros Simpler code, because the state of local variables and control flow are preserved for each call. A generator uses less memory than a function that creates an entire list of values at once. 2.9.3 Cons None. 2.9.4 Decision Fine. Use "Yields:" rather than "Returns:" in the docstring for generator functions. 2.10 Lambda Functions Okay for one-liners. 2.10.1 Definition Lambdas define anonymous functions in an expression, as opposed to a statement. They are often used to define callbacks or operators for higher-order functions like map() and filter(). 2.10.2 Pros Convenient. 2.10.3 Cons Harder to read and debug than local functions. The lack of names means stack traces are more difficult to understand. Expressiveness is limited because the function may only contain an expression. 2.10.4 Decision Okay to use them for one-liners. If the code inside the lambda function is longer than 60-80 chars, it's probably better to define it as a regular nested function. For common operations like multiplication, use the functions from the operator module instead of lambda functions. For example, prefer operator.mul to lambda x, y: x * y. 2.11 Conditional Expressions Okay for one-liners. 2.11.1 Definition Conditional expressions (sometimes called a "ternary operator") are mechanisms that provide a shorter syntax for if statements. For example: x = 1 if cond else 2. 2.11.2 Pros Shorter and more convenient than an if statement. 2.11.3 Cons May be harder to read than an if statement. The condition may be difficult to locate if the expression is long. 2.11.4 Decision Okay to use for one-liners. In other cases prefer to use a complete if statement. 2.12 Default Argument Values Okay in most cases. 2.12.1 Definition You can specify values for variables at the end of a function's parameter list, e.g., def foo(a, b=0):. If foo is called with only one argument, b is set to 0. If it is called with two arguments, b has the value of the second argument. 2.12.2 Pros Often you have a function that uses lots of default values, but-rarely-you want to override the defaults. Default argument values provide an easy way to do this, without having to define lots of functions for the rare exceptions. Also, Python does not support overloaded methods/functions and default arguments are an easy way of "faking" the overloading behavior. 2.12.3 Cons Default arguments are evaluated once at module load time. This may cause problems if the argument is a mutable object such as a list or a dictionary. If the function modifies the object (e.g., by appending an item to a list), the default value is modified. 2.12.4 Decision Okay to use with the following caveat: Do not use mutable objects as default values in the function or method definition. Yes: def foo(a, b=None): if b is None: b = [] Yes: def foo(a, b: Optional[Sequence] = None): if b is None: b = [] Yes: def foo(a, b: Sequence = ()): # Empty tuple OK since tuples are immutable ... No: def foo(a, b=[]): ... No: def foo(a, b=time.time()): # The time the module was loaded??? ... No: def foo(a, b=FLAGS.my_thing): # sys.argv has not yet been parsed... ... 2.13 Properties Use properties for accessing or setting data where you would normally have used simple, lightweight accessor or setter methods. 2.13.1 Definition A way to wrap method calls for getting and setting an attribute as a standard attribute access when the computation is lightweight. 2.13.2 Pros Readability is increased by eliminating explicit get and set method calls for simple attribute access. Allows calculations to be lazy. Considered the Pythonic way to maintain the interface of a class. In terms of performance, allowing properties bypasses needing trivial accessor methods when a direct variable access is reasonable. This also allows accessor methods to be added in the future without breaking the interface. 2.13.3 Cons Must inherit from object in Python 2. Can hide side-effects much like operator overloading. Can be confusing for subclasses. 2.13.4 Decision Use properties in new code to access or set data where you would normally have used simple, lightweight accessor or setter methods. Properties should be created with the @property decorator. Inheritance with properties can be non-obvious if the property itself is not overridden. Thus one must make sure that accessor methods are called indirectly to ensure methods overridden in subclasses are called by the property (using the Template Method DP). Yes: import math class Square(object): """A square with two properties: a writable area and a read-only perimeter. To use: >>> sq = Square(3) >>> sq.area 9 >>> sq.perimeter 12 >>> sq.area = 16 >>> sq.side 4 >>> sq.perimeter 16 """ def __init__(self, side): self.side = side @property def area(self): """Gets or sets the area of the square.""" return self._get_area() @area.setter def area(self, area): return self._set_area(area) def _get_area(self): """Indirect accessor to calculate the 'area' property.""" return self.side ** 2 def _set_area(self, area): """Indirect setter to set the 'area' property.""" self.side = math.sqrt(area) @property def perimeter(self): return self.side * 4 2.14 True/False evaluations Use the "implicit" false if at all possible. 2.14.1 Definition Python evaluates certain values as False when in a boolean context. A quick "rule of thumb" is that all "empty" values are considered false, so 0, None, [], {}, '' all evaluate as false in a boolean context. 2.14.2 Pros Conditions using Python booleans are easier to read and less error-prone. In most cases, they're also faster. 2.14.3 Cons May look strange to C/C++ developers. 2.14.4 Decision Use the "implicit" false if at all possible, e.g., if foo: rather than if foo != []:. There are a few caveats that you should keep in mind though: Never use == or != to compare singletons like None. Use is or is not. Beware of writing if x: when you really mean if x is not None:-e.g., when testing whether a variable or argument that defaults to None was set to some other value. The other value might be a value that's false in a boolean context! Never compare a boolean variable to False using ==. Use if not x: instead. If you need to distinguish False from None then chain the expressions, such as if not x and x is not None:. For sequences (strings, lists, tuples), use the fact that empty sequences are false, so if seq: and if not seq: are preferable to if len(seq): and if not len(seq): respectively. When handling integers, implicit false may involve more risk than benefit (i.e., accidentally handling None as 0). You may compare a value which is known to be an integer (and is not the result of len()) against the integer 0. Yes: if not users: print('no users') if foo == 0: self.handle_zero() if i % 10 == 0: self.handle_multiple_of_ten() def f(x=None): if x is None: x = [] No: if len(users) == 0: print('no users') if foo is not None and not foo: self.handle_zero() if not i % 10: self.handle_multiple_of_ten() def f(x=None): x = x or [] Note that '0' (i.e., 0 as string) evaluates to true. 2.15 Deprecated Language Features Use string methods instead of the string module where possible. Use function call syntax instead of apply. Use list comprehensions and for loops instead of filter and map when the function argument would have been an inlined lambda anyway. Use for loops instead of reduce. 2.15.1 Definition Current versions of Python provide alternative constructs that people find generally preferable. 2.15.2 Decision We do not use any Python version which does not support these features, so there is no reason not to use the new styles. Yes: words = foo.split(':') [x[1] for x in my_list if x[2] == 5] map(math.sqrt, data) # Ok. No inlined lambda expression. fn(*args, **kwargs) No: words = string.split(foo, ':') map(lambda x: x[1], filter(lambda x: x[2] == 5, my_list)) apply(fn, args, kwargs) 2.16 Lexical Scoping Okay to use. 2.16.1 Definition A nested Python function can refer to variables defined in enclosing functions, but can not assign to them. Variable bindings are resolved using lexical scoping, that is, based on the static program text. Any assignment to a name in a block will cause Python to treat all references to that name as a local variable, even if the use precedes the assignment. If a global declaration occurs, the name is treated as a global variable. An example of the use of this feature is: def get_adder(summand1): """Returns a function that adds numbers to a given number.""" def adder(summand2): return summand1 + summand2 return adder 2.16.2 Pros Often results in clearer, more elegant code. Especially comforting to experienced Lisp and Scheme (and Haskell and ML and ...) programmers. 2.16.3 Cons Can lead to confusing bugs. Such as this example based on PEP-0227: i = 4 def foo(x): def bar(): print(i, end='') # ... # A bunch of code here # ... for i in x: # Ah, i *is* local to foo, so this is what bar sees print(i, end='') bar() So foo([1, 2, 3]) will print 1 2 3 3, not 1 2 3 4. 2.16.4 Decision Okay to use. 2.17 Function and Method Decorators Use decorators judiciously when there is a clear advantage. Avoid @staticmethod and limit use of @classmethod. 2.17.1 Definition Decorators for Functions and Methods (a.k.a "the @ notation"). One common decorator is @property, used for converting ordinary methods into dynamically computed attributes. However, the decorator syntax allows for user-defined decorators as well. Specifically, for some function my_decorator, this: class C(object): @my_decorator def method(self): # method body ... is equivalent to: class C(object): def method(self): # method body ... method = my_decorator(method) 2.17.2 Pros Elegantly specifies some transformation on a method; the transformation might eliminate some repetitive code, enforce invariants, etc. 2.17.3 Cons Decorators can perform arbitrary operations on a function's arguments or return values, resulting in surprising implicit behavior. Additionally, decorators execute at import time. Failures in decorator code are pretty much impossible to recover from. 2.17.4 Decision Use decorators judiciously when there is a clear advantage. Decorators should follow the same import and naming guidelines as functions. Decorator pydoc should clearly state that the function is a decorator. Write unit tests for decorators. Avoid external dependencies in the decorator itself (e.g. don't rely on files, sockets, database connections, etc.), since they might not be available when the decorator runs (at import time, perhaps from pydoc or other tools). A decorator that is called with valid parameters should (as much as possible) be guaranteed to succeed in all cases. Decorators are a special case of "top level code" - see main for more discussion. Never use @staticmethod unless forced to in order to integrate with an API defined in an existing library. Write a module level function instead. Use @classmethod only when writing a named constructor or a class-specific routine that modifies necessary global state such as a process-wide cache. 2.18 Threading Do not rely on the atomicity of built-in types. While Python's built-in data types such as dictionaries appear to have atomic operations, there are corner cases where they aren't atomic (e.g. if __hash__ or __eq__ are implemented as Python methods) and their atomicity should not be relied upon. Neither should you rely on atomic variable assignment (since this in turn depends on dictionaries). Use the Queue module's Queue data type as the preferred way to communicate data between threads. Otherwise, use the threading module and its locking primitives. Learn about the proper use of condition variables so you can use threading.Condition instead of using lower-level locks. 2.19 Power Features Avoid these features. 2.19.1 Definition Python is an extremely flexible language and gives you many fancy features such as custom metaclasses, access to bytecode, on-the-fly compilation, dynamic inheritance, object reparenting, import hacks, reflection (e.g. some uses of getattr()), modification of system internals, etc. 2.19.2 Pros These are powerful language features. They can make your code more compact. 2.19.3 Cons It's very tempting to use these "cool" features when they're not absolutely necessary. It's harder to read, understand, and debug code that's using unusual features underneath. It doesn't seem that way at first (to the original author), but when revisiting the code, it tends to be more difficult than code that is longer but is straightforward. 2.19.4 Decision Avoid these features in your code. Standard library modules and classes that internally use these features are okay to use (for example, abc.ABCMeta, collections.namedtuple, dataclasses, and enum). 2.20 Modern Python: Python 3 and from __future__ imports Python 3 is here! While not every project is ready to use it yet, all code should be written to be 3 compatible (and tested under 3 when possible). 2.20.1 Definition Python 3 is a significant change in the Python language. While existing code is often written with 2.7 in mind, there are some simple things to do to make code more explicit about its intentions and thus better prepared for use under Python 3 without modification. 2.20.2 Pros Code written with Python 3 in mind is more explicit and easier to get running under Python 3 once all of the dependencies of your project are ready. 2.20.3 Cons Some people find the additional boilerplate to be ugly. It's unusual to add imports to a module that doesn't actually require the features added by the import. 2.20.4 Decision from __future__ imports Use of from __future__ import statements is encouraged. All new code should contain the following and existing code should be updated to be compatible when possible: from __future__ import absolute_import from __future__ import division from __future__ import print_function If you are not already familiar with those, read up on each here: absolute imports, new / division behavior, and the print function. Please don't omit or remove these imports, even if they're not currently used in the module. It is better to always have the future imports in all files so that they are not forgotten during later edits when someone starts using such a feature. There are other from __future__ import statements. Use them as you see fit. We do not include unicode_literals in our recommendations as it is not a clear win due to implicit default codec conversion consequences it introduces in many places within Python 2.7. Most code is better off with explicit use of b'' and u'' bytes and unicode string literals as necessary. The six, future, or past libraries. When your project needs to actively support use under both Python 2 and 3, use of these libraries is encouraged as you see fit. They exist to make your code cleaner and life easier. 2.21 Type Annotated Code You can annotate Python 3 code with type hints according to PEP-484, and type-check the code at build time with a type checking tool like pytype. Type annotations can be in the source or in a stub pyi file. Whenever possible, annotations should be in the source. Use pyi files for third-party or extension modules. 2.21.1 Definition Type annotations (or "type hints") are for function or method arguments and return values: def func(a: int) -> List[int]: You can also declare the type of a variable using a special comment: a = SomeFunc() # type: SomeType 2.21.2 Pros Type annotations improve the readability and maintainability of your code. The type checker will convert many runtime errors to build-time errors, and reduce your ability to use Power Features. 2.21.3 Cons You will have to keep the type declarations up to date. You might see type errors that you think are valid code. Use of a type checker may reduce your ability to use Power Features. 2.21.4 Decision This highly depends on the complexity of your project. Give it a try. 3 Python Style Rules 3.1 Semicolons Do not terminate your lines with semicolons, and do not use semicolons to put two statements on the same line. 3.2 Line length Maximum line length is 80 characters. Exceptions: Long import statements. URLs, pathnames, or long flags in comments. Long string module level constants not containing whitespace that would be inconvenient to split across lines such as URLs or pathnames. Pylint disable comments. (e.g.: # pylint: disable=invalid-name) Do not use backslash line continuation except for with statements requiring three or more context managers. Make use of Python's implicit line joining inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression. Yes: foo_bar(self, width, height, color='black', design=None, x='foo', emphasis=None, highlight=0) if (width == 0 and height == 0 and color == 'red' and emphasis == 'strong'): When a literal string won't fit on a single line, use parentheses for implicit line joining. x = ('This will build a very long long ' 'long long long long long long string') Within comments, put long URLs on their own line if necessary. Yes: # See details at # http://www.example.com/us/developer/documentation/api/content/v2.0/csv_file_name_extension_full_specification.html No: # See details at # http://www.example.com/us/developer/documentation/api/content/\ # v2.0/csv_file_name_extension_full_specification.html It is permissible to use backslash continuation when defining a with statement whose expressions span three or more lines. For two lines of expressions, use a nested with statement: Yes: with very_long_first_expression_function() as spam, \ very_long_second_expression_function() as beans, \ third_thing() as eggs: place_order(eggs, beans, spam, beans) No: with VeryLongFirstExpressionFunction() as spam, \ VeryLongSecondExpressionFunction() as beans: PlaceOrder(eggs, beans, spam, beans) Yes: with very_long_first_expression_function() as spam: with very_long_second_expression_function() as beans: place_order(beans, spam) Make note of the indentation of the elements in the line continuation examples above; see the indentation section for explanation. 3.3 Parentheses Use parentheses sparingly. It is fine, though not required, to use parentheses around tuples. Do not use them in return statements or conditional statements unless using parentheses for implied line continuation or to indicate a tuple. Yes: if foo: bar() while x: x = bar() if x and y: bar() if not x: bar() # For a 1 item tuple the ()s are more visually obvious than the comma. onesie = (foo,) return foo return spam, beans return (spam, beans) for (x, y) in dict.items(): ... No: if (x): bar() if not(x): bar() return (foo) 3.4 Indentation Indent your code blocks with 4 spaces. Never use tabs or mix tabs and spaces. In cases of implied line continuation, you should align wrapped elements either vertically, as per the examples in the line length section; or using a hanging indent of 4 spaces, in which case there should be nothing after the open parenthesis or bracket on the first line. Yes: # Aligned with opening delimiter foo = long_function_name(var_one, var_two, var_three, var_four) meal = (spam, beans) # Aligned with opening delimiter in a dictionary foo = { long_dictionary_key: value1 + value2, ... } # 4-space hanging indent; nothing on first line foo = long_function_name( var_one, var_two, var_three, var_four) meal = ( spam, beans) # 4-space hanging indent in a dictionary foo = { long_dictionary_key: long_dictionary_value, ... } No: # Stuff on first line forbidden foo = long_function_name(var_one, var_two, var_three, var_four) meal = (spam, beans) # 2-space hanging indent forbidden foo = long_function_name( var_one, var_two, var_three, var_four) # No hanging indent in a dictionary foo = { long_dictionary_key: long_dictionary_value, ... } 3.4.1 Trailing commas in sequences of items? Trailing commas in sequences of items are recommended only when the closing container token ], ), or } does not appear on the same line as the final element. The presence of a trailing comma is also used as a hint to our Python code auto-formatter YAPF to direct it to auto-format the container of items to one item per line when the , after the final element is present. Yes: golomb3 = [0, 1, 3] Yes: golomb4 = [ 0, 1, 4, 6, ] No: golomb4 = [ 0, 1, 4, 6 ] 3.5 Blank Lines Two blank lines between top-level definitions, be they function or class definitions. One blank line between method definitions and between the class line and the first method. No blank line following a def line. Use single blank lines as you judge appropriate within functions or methods. 3.6 Whitespace Follow standard typographic rules for the use of spaces around punctuation. No whitespace inside parentheses, brackets or braces. Yes: spam(ham[1], {eggs: 2}, []) No: spam( ham[ 1 ], { eggs: 2 }, [ ] ) No whitespace before a comma, semicolon, or colon. Do use whitespace after a comma, semicolon, or colon, except at the end of the line. Yes: if x == 4: print(x, y) x, y = y, x No: if x == 4 : print(x , y) x , y = y , x No whitespace before the open paren/bracket that starts an argument list, indexing or slicing. Yes: spam(1) No: spam (1) Yes: dict['key'] = list[index] No: dict ['key'] = list [index] Surround binary operators with a single space on either side for assignment (=), comparisons (==, <, >, !=, <>, <=, >=, in, not in, is, is not), and Booleans (and, or, not). Use your better judgment for the insertion of spaces around arithmetic operators (+, -, *, /, //, %, **, @). Yes: x == 1 No: x<1 Never use spaces around = when passing keyword arguments or defining a default parameter value, with one exception: when a type annotation is present, do use spaces around the = for the default parameter value. Yes: def complex(real, imag=0.0): return Magic(r=real, i=imag) Yes: def complex(real, imag: float = 0.0): return Magic(r=real, i=imag) No: def complex(real, imag = 0.0): return Magic(r = real, i = imag) No: def complex(real, imag: float=0.0): return Magic(r = real, i = imag) Don't use spaces to vertically align tokens on consecutive lines, since it becomes a maintenance burden (applies to :, #, =, etc.): Yes: foo = 1000 # comment long_name = 2 # comment that should not be aligned dictionary = { 'foo': 1, 'long_name': 2, } No: foo = 1000 # comment long_name = 2 # comment that should not be aligned dictionary = { 'foo' : 1, 'long_name': 2, } 3.7 Shebang Line Most .py files do not need to start with a #! line. Start the main file of a program with #!/usr/bin/python with an optional single digit 2 or 3 suffix per PEP-394. This line is used by the kernel to find the Python interpreter, but is ignored by Python when importing modules. It is only necessary on a file that will be executed directly. 3.8 Comments and Docstrings Be sure to use the right style for module, function, method docstrings and inline comments. 3.8.1 Docstrings Python uses docstrings to document code. A docstring is a string that is the first statement in a package, module, class or function. These strings can be extracted automatically through the __doc__ member of the object and are used by pydoc. (Try running pydoc on your module to see how it looks.) Always use the three double-quote """ format for docstrings (per PEP 257). A docstring should be organized as a summary line (one physical line) terminated by a period, question mark, or exclamation point, followed by a blank line, followed by the rest of the docstring starting at the same cursor position as the first quote of the first line. There are more formatting guidelines for docstrings below. 3.8.2 Modules Every file should contain license boilerplate. Choose the appropriate boilerplate for the license used by the project (for example, Apache 2.0, BSD, LGPL, GPL) 3.8.3 Functions and Methods In this section, "function" means a method, function, or generator. A function must have a docstring, unless it meets all of the following criteria: not externally visible very short obvious A docstring should give enough information to write a call to the function without reading the function's code. The docstring should be descriptive ("""Fetches rows from a Bigtable.""") rather than imperative ("""Fetch rows from a Bigtable."""). A docstring should describe the function's calling syntax and its semantics, not its implementation. For tricky code, comments alongside the code are more appropriate than using docstrings. A method that overrides a method from a base class may have a simple docstring sending the reader to its overridden method's docstring, such as """See base class.""". The rationale is that there is no need to repeat in many places documentation that is already present in the base method's docstring. However, if the overriding method's behavior is substantially different from the overridden method, or details need to be provided (e.g., documenting additional side effects), a docstring with at least those differences is required on the overriding method. Certain aspects of a function should be documented in special sections, listed below. Each section begins with a heading line, which ends with a colon. Sections should be indented two spaces, except for the heading. Args: List each parameter by name. A description should follow the name, and be separated by a colon and a space. If the description is too long to fit on a single 80-character line, use a hanging indent of 2 or 4 spaces (be consistent with the rest of the file). The description should include required type(s) if the code does not contain a corresponding type annotation. If a function accepts *foo (variable length argument lists) and/or **bar (arbitrary keyword arguments), they should be listed as *foo and **bar. Returns: (or Yields: for generators) Describe the type and semantics of the return value. If the function only returns None, this section is not required. It may also be omitted if the docstring starts with Returns or Yields (e.g. """Returns row from Bigtable as a tuple of strings.""") and the opening sentence is sufficient to describe return value. Raises: List all exceptions that are relevant to the interface. def fetch_bigtable_rows(big_table, keys, other_silly_variable=None): """Fetches rows from a Bigtable. Retrieves rows pertaining to the given keys from the Table instance represented by big_table. Silly things may happen if other_silly_variable is not None. Args: big_table: An open Bigtable Table instance. keys: A sequence of strings representing the key of each table row to fetch. other_silly_variable: Another optional variable, that has a much longer name than the other args, and which does nothing. Returns: A dict mapping keys to the corresponding table row data fetched. Each row is represented as a tuple of strings. For example: {'Serak': ('Rigel VII', 'Preparer'), 'Zim': ('Irk', 'Invader'), 'Lrrr': ('Omicron Persei 8', 'Emperor')} If a key from the keys argument is missing from the dictionary, then that row was not found in the table. Raises: IOError: An error occurred accessing the bigtable.Table object. """ 3.8.4 Classes Classes should have a docstring below the class definition describing the class. If your class has public attributes, they should be documented here in an Attributes section and follow the same formatting as a function's Args section. class SampleClass(object): """Summary of class here. Longer class information.... Longer class information.... Attributes: likes_spam: A boolean indicating if we like SPAM or not. eggs: An integer count of the eggs we have laid. """ def __init__(self, likes_spam=False): """Inits SampleClass with blah.""" self.likes_spam = likes_spam self.eggs = 0 def public_method(self): """Performs operation blah.""" 3.8.5 Block and Inline Comments The final place to have comments is in tricky parts of the code. If you're going to have to explain it at the next code review, you should comment it now. Complicated operations get a few lines of comments before the operations commence. Non-obvious ones get comments at the end of the line. # We use a weighted dictionary search to find out where i is in # the array. We extrapolate position based on the largest num # in the array and the array size and then do binary search to # get the exact number. if i & (i-1) == 0: # True if i is 0 or a power of 2. To improve legibility, these comments should be at least 2 spaces away from the code. On the other hand, never describe the code. Assume the person reading the code knows Python (though not what you're trying to do) better than you do. # BAD COMMENT: Now go through the b array and make sure whenever i occurs # the next element is i+1 3.8.6 Punctuation, Spelling and Grammar Pay attention to punctuation, spelling, and grammar; it is easier to read well-written comments than badly written ones. Comments should be as readable as narrative text, with proper capitalization and punctuation. In many cases, complete sentences are more readable than sentence fragments. Shorter comments, such as comments at the end of a line of code, can sometimes be less formal, but you should be consistent with your style. Although it can be frustrating to have a code reviewer point out that you are using a comma when you should be using a semicolon, it is very important that source code maintain a high level of clarity and readability. Proper punctuation, spelling, and grammar help with that goal. 3.9 Classes If a class inherits from no other base classes, explicitly inherit from object. This also applies to nested classes. Yes: class SampleClass(object): pass class OuterClass(object): class InnerClass(object): pass class ChildClass(ParentClass): """Explicitly inherits from another class already.""" No: class SampleClass: pass class OuterClass: class InnerClass: pass Inheriting from object is needed to make properties work properly in Python 2 and can protect your code from potential incompatibility with Python 3. It also defines special methods that implement the default semantics of objects including __new__, __init__, __delattr__, __getattribute__, __setattr__, __hash__, __repr__, and __str__. 3.10 Strings Use the format method or the % operator for formatting strings, even when the parameters are all strings. Use your best judgement to decide between + and % (or format) though. Yes: x = a + b x = '%s, %s!' % (imperative, expletive) x = '{}, {}'.format(first, second) x = 'name: %s; score: %d' % (name, n) x = 'name: {}; score: {}'.format(name, n) x = f'name: {name}; score: {n}' # Python 3.6+ No: x = '%s%s' % (a, b) # use + in this case x = '{}{}'.format(a, b) # use + in this case x = first + ', ' + second x = 'name: ' + name + '; score: ' + str(n) Avoid using the + and += operators to accumulate a string within a loop. Since strings are immutable, this creates unnecessary temporary objects and results in quadratic rather than linear running time. Instead, add each substring to a list and ''.join the list after the loop terminates (or, write each substring to a io.BytesIO buffer). Yes: items = ['<table>'] for last_name, first_name in employee_list: items.append('<tr><td>%s, %s</td></tr>' % (last_name, first_name)) items.append('</table>') employee_table = ''.join(items) No: employee_table = '<table>' for last_name, first_name in employee_list: employee_table += '<tr><td>%s, %s</td></tr>' % (last_name, first_name) employee_table += '</table>' Be consistent with your choice of string quote character within a file. Pick ' or " and stick with it. It is okay to use the other quote character on a string to avoid the need to \\ escape within the string. gpylint enforces this. Yes: Python('Why are you hiding your eyes?') Gollum("I'm scared of lint errors.") Narrator('"Good!" thought a happy Python reviewer.') No: Python("Why are you hiding your eyes?") Gollum('The lint. It burns. It burns us.') Gollum("Always the great lint. Watching. Watching.") Prefer """ for multi-line strings rather than '''. Projects may choose to use ''' for all non-docstring multi-line strings if and only if they also use ' for regular strings. Docstrings must use """ regardless. Note that it is often cleaner to use implicit line joining since multi-line strings do not flow with the indentation of the rest of the program: Yes: print("This is much nicer.\n" "Do it this way.\n") No: print("""This is pretty ugly. Don't do this. """) 3.11 Files and Sockets Explicitly close files and sockets when done with them. Leaving files, sockets or other file-like objects open unnecessarily has many downsides: They may consume limited system resources, such as file descriptors. Code that deals with many such objects may exhaust those resources unnecessarily if they're not returned to the system promptly after use. Holding files open may prevent other actions such as moving or deleting them. Files and sockets that are shared throughout a program may inadvertently be read from or written to after logically being closed. If they are actually closed, attempts to read or write from them will throw exceptions, making the problem known sooner. Furthermore, while files and sockets are automatically closed when the file object is destructed, tying the lifetime of the file object to the state of the file is poor practice: There are no guarantees as to when the runtime will actually run the file's destructor. Different Python implementations use different memory management techniques, such as delayed Garbage Collection, which may increase the object's lifetime arbitrarily and indefinitely. Unexpected references to the file, e.g. in globals or exception tracebacks, may keep it around longer than intended. The preferred way to manage files is using the "with" statement: with open("hello.txt") as hello_file: for line in hello_file: print(line) For file-like objects that do not support the "with" statement, use contextlib.closing(): import contextlib with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page: for line in front_page: print(line) 3.12 TODO Comments Use TODO comments for code that is temporary, a short-term solution, or good-enough but not perfect. A TODO comment begins with the string TODO in all caps and a parenthesized name, e-mail address, or other identifier of the person or issue with the best context about the problem. This is followed by an explanation of what there is to do. The purpose is to have a consistent TODO format that can be searched to find out how to get more details. A TODO is not a commitment that the person referenced will fix the problem. Thus when you create a TODO, it is almost always your name that is given. # TODO([email protected]): Use a "*" here for string repetition. # TODO(Zeke) Change this to use relations. If your TODO is of the form "At a future date do something" make sure that you either include a very specific date ("Fix by November 2009") or a very specific event ("Remove this code when all clients can handle XML responses."). 3.13 Imports formatting Imports should be on separate lines. E.g.: Yes: import os import sys No: import os, sys Imports are always put at the top of the file, just after any module comments and docstrings and before module globals and constants. Imports should be grouped from most generic to least generic: Python standard library imports. For example: import sys third-party module or package imports. For example: import tensorflow as tf Code repository sub-package imports. For example: from otherproject.ai import mind Deprecated: application-specific imports that are part of the same top level sub-package as this file. For example: from myproject.backend.hgwells import time_machine You may find older Google Python Style code doing this, but it is no longer required. New code is encouraged not to bother with this. Simply treat application-specific sub-package imports the same as other sub-package imports. Within each grouping, imports should be sorted lexicographically, ignoring case, according to each module's full package path. Code may optionally place a blank line between import sections. import collections import queue import sys from absl import app from absl import flags import bs4 import cryptography import tensorflow as tf from book.genres import scifi from myproject.backend.hgwells import time_machine from myproject.backend.state_machine import main_loop from otherproject.ai import body from otherproject.ai import mind from otherproject.ai import soul # Older style code may have these imports down here instead: #from myproject.backend.hgwells import time_machine #from myproject.backend.state_machine import main_loop 3.14 Statements Generally only one statement per line. However, you may put the result of a test on the same line as the test only if the entire statement fits on one line. In particular, you can never do so with try/except since the try and except can't both fit on the same line, and you can only do so with an if if there is no else. Yes: if foo: bar(foo) No: if foo: bar(foo) else: baz(foo) try: bar(foo) except ValueError: baz(foo) try: bar(foo) except ValueError: baz(foo) 3.15 Access Control If an accessor function would be trivial, you should use public variables instead of accessor functions to avoid the extra cost of function calls in Python. When more functionality is added you can use property to keep the syntax consistent. On the other hand, if access is more complex, or the cost of accessing the variable is significant, you should use function calls (following the Naming guidelines) such as get_foo() and set_foo(). If the past behavior allowed access through a property, do not bind the new accessor functions to the property. Any code still attempting to access the variable by the old method should break visibly so they are made aware of the change in complexity. 3.16 Naming module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name. Function names, variable names, and filenames should be descriptive; eschew abbreviation. In particular, do not use abbreviations that are ambiguous or unfamiliar to readers outside your project, and do not abbreviate by deleting letters within a word. Always use a .py filename extension. Never use dashes. 3.16.1 Names to Avoid single character names except for counters or iterators. You may use "e" as an exception identifier in try/except statements. dashes (-) in any package/module name __double_leading_and_trailing_underscore__ names (reserved by Python) 3.16.2 Naming Convention "Internal" means internal to a module, or protected or private within a class. Prepending a single underscore (_) has some support for protecting module variables and functions (not included with from module import *). While prepending a double underscore (__ aka "dunder") to an instance variable or method effectively makes the variable or method private to its class (using name mangling) we discourage its use as it impacts readability and testability and isn't really private. Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module. Use CapWords for class names, but lower_with_under.py for module names. Although there are some old modules named CapWords.py, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait - did I write import StringIO or from StringIO import StringIO?") Underscores may appear in unittest method names starting with test to separate logical components of the name, even if those components use CapWords. One possible pattern is test<MethodUnderTest>_<state>; for example testPop_EmptyStack is okay. There is no One Correct Way to name test methods. 3.16.3 File Naming Python filenames must have a .py extension and must not contain dashes (-). This allows them to be imported and unittested. If you want an executable to be accessible without the extension, use a symbolic link or a simple bash wrapper containing exec "$0.py" "$@". 3.16.4 Guidelines derived from Guido's Recommendations Type Public Internal Packages lower_with_under Modules lower_with_under _lower_with_under Classes CapWords _CapWords Exceptions CapWords Functions lower_with_under() _lower_with_under() Global/Class Constants CAPS_WITH_UNDER _CAPS_WITH_UNDER Global/Class Variables lower_with_under _lower_with_under Instance Variables lower_with_under _lower_with_under (protected) Method Names lower_with_under() _lower_with_under() (protected) Function/Method Parameters lower_with_under Local Variables lower_with_under While Python supports making things private by using a leading double underscore __ (aka. "dunder") prefix on a name, this is discouraged. Prefer the use of a single underscore. They are easier to type, read, and to access from small unittests. Lint warnings take care of invalid access to protected members. 3.17 Main Even a file meant to be used as an executable should be importable and a mere import should not have the side effect of executing the program's main functionality. The main functionality should be in a main() function. In Python, pydoc as well as unit tests require modules to be importable. Your code should always check if __name__ == '__main__' before executing your main program so that the main program is not executed when the module is imported. def main(): ... if __name__ == '__main__': main() All code at the top level will be executed when the module is imported. Be careful not to call functions, create objects, or perform other operations that should not be executed when the file is being pydoced. 3.18 Function length Prefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on function length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. 3.19 Type Annotations 3.19.1 General Rules Familiarize yourself with PEP-484. In methods, only annotate self, or cls if it is necessary for proper type information. e.g., @classmethod def create(cls: Type[T]) -> T: return cls() If any other variable or a returned type should not be expressed, use Any. You are not required to annotate all the functions in a module. At least annotate your public APIs. Use judgment to get to a good balance between safety and clarity on the one hand, and flexibility on the other. Annotate code that is prone to type-related errors (previous bugs or complexity). Annotate code that is hard to understand. Annotate code as it becomes stable from a types perspective. In many cases, you can annotate all the functions in mature code without losing too much flexibility. 3.19.2 Line Breaking Try to follow the existing indentation rules. After annotating, many function signatures will become "one parameter per line". def my_method(self, first_var: int, second_var: Foo, third_var: Optional[Bar]) -> int: ... Always prefer breaking between variables, and not for example between variable names and type annotations. However, if everything fits on the same line, go for it. def my_method(self, first_var: int) -> int: ... If the combination of the function name, the last parameter, and the return type is too long, indent by 4 in a new line. def my_method( self, first_var: int) -> Tuple[MyLongType1, MyLongType1]: ... When the return type does not fit on the same line as the last parameter, the preferred way is to indent the parameters by 4 on a new line and align the closing parenthesis with the def. Yes: def my_method( self, **kw_args: Optional[MyLongType] ) -> Dict[OtherLongType, MyLongType]: ... pylint allows you to move the closing parenthesis to a new line and align with the opening one, but this is less readable. No: def my_method(self, **kw_args: Optional[MyLongType] ) -> Dict[OtherLongType, MyLongType]: ... As in the examples above, prefer not to break types. However, sometimes they are too long to be on a single line (try to keep sub-types unbroken). def my_method( self, first_var: Tuple[List[MyLongType1], List[MyLongType2]], second_var: List[Dict[ MyLongType3, MyLongType4]]) -> None: ... If a single name and type is too long, consider using an alias for the type. The last resort is to break after the colon and indent by 4. Yes: def my_function( long_variable_name: long_module_name.LongTypeName, ) -> None: ... No: def my_function( long_variable_name: long_module_name. LongTypeName, ) -> None: ... 3.19.3 Forward Declarations If you need to use a class name from the same module that is not yet defined - for example, if you need the class inside the class declaration, or if you use a class that is defined below - use a string for the class name. class MyClass(object): def __init__(self, stack: List["MyClass"]) -> None: 3.19.4 Default Values As per PEP-008, use spaces around the = only for arguments that have both a type annotation and a default value. Yes: def func(a: int = 0) -> int: ... No: def func(a:int=0) -> int: ... 3.19.5 NoneType In the Python type system, NoneType is a "first class" type, and for typing purposes, None is an alias for NoneType. If an argument can be None, it has to be declared! You can use Union, but if there is only one other type, use Optional. Use explicit Optional instead of implicit Optional. Earlier versions of PEP 484 allowed a: Text = None to be interpretted as a: Optional[Text] = None, but that is no longer the preferred behavior. Yes: def func(a: Optional[Text], b: Optional[Text] = None) -> Text: ... def multiple_nullable_union(a: Union[None, Text, int]) -> Text ... No: def nullable_union(a: Union[None, Text]) -> Text: ... def implicit_optional(a: Text = None) -> Text: ... 3.19.6 Type Aliases You can declare aliases of complex types. The name of an alias should be CapWorded. If the alias is used only in this module, it should be _Private. For example, if the name of module together with the type is too long: _ShortName = module_with_long_name.TypeWithLongName ComplexMap = Mapping[Text, List[Tuple[int, int]]] Other examples are complex nested types and multiple return variables from a function (as a tuple). 3.19.7 Ignoring Types You can disable type checking on a line with the special comment # type: ignore. pytype has a disable option for specific errors (similar to lint): # pytype: disable=attribute-error 3.19.8 Typing internal variables If an internal variable has a type that is hard or impossible to infer, you can supply it as a special comment: a = SomeUndecoratedFunction() # type: Foo 3.19.9 Tuples vs Lists Unlike Lists, which can only have a single type, Tuples can have either a single repeated type or a set number of elements with different types. The latter is commonly used as return type from a function. a = [1, 2, 3] # type: List[int] b = (1, 2, 3) # type: Tuple[int, ...] c = (1, "2", 3.5) # type: Tuple[int, Text, float] 3.19.10 TypeVar The Python type system has generics. The factory function TypeVar is a common way to use them. Example: from typing import List, TypeVar T = TypeVar("T") ... def next(l: List[T]) -> T: return l.pop() A TypeVar can be constrained: AddableType = TypeVar("AddableType", int, float, Text) def add(a: AddableType, b: AddableType) -> AddableType: return a + b A common predefined type variable in the typing module is AnyStr. Use it for multiple annotations that can be bytes or unicode and must all be the same type. from typing import AnyStr def check_length(x: AnyStr) -> AnyStr: if len(x) <= 42: return x raise ValueError() 3.19.11 String types The proper type for annotating strings depends on what versions of Python the code is intended for. For Python 3 only code, prefer to use str. Text is also acceptable. Be consistent in using one or the other. For Python 2 compatible code, use Text. In some rare cases, str may make sense; typically to aid compatiblity when the return types aren't the same between the two Python versions. Avoid using unicode: it doesn't exist in Python 3. The reason this discreprency exists is because str means different things depending on the Python version. No: def py2_code(x: str) -> unicode: ... For code that deals with binary data, use bytes. def deals_with_binary_data(x: bytes) -> bytes: ... For Python 2 compatible code that processes text data (str or unicode in Python 2, str in Python 3), use Text. For Python 3 only code that process text data, prefer str. from typing import Text ... def py2_compatible(x: Text) -> Text: ... def py3_only(x: str) -> str: ... If the type can be either bytes or text, use Union, with the appropriate text type. from typing import Text, Union ... def py2_compatible(x: Union[bytes, Text]) -> Union[bytes, Text]: ... def py3_only(x: Union[bytes, str]) -> Union[bytes, str]: ... If all the string types of a function are always the same, for example if the return type is the same as the argument type in the code above, use AnyStr. Writing it like this will simplify the process of porting the code to Python 3. 3.19.12 Imports For Typing For classes from the typing module, always import the class itself. You are explicitly allowed to import multiple specific classes on one line from the typing module. Ex: from typing import Any, Dict, Optional Given that this way of importing from typing adds items to the local namespace, any names in typing should be treated similarly to keywords, and not be defined in your Python code, typed or not. If there is a collision between a type and an existing name in a module, import it using import x as y. from typing import Any as AnyType 3.19.13 Conditional Imports Use conditional imports only in exceptional cases where the additional imports needed for type checking must be avoided at runtime. This pattern is discouraged; alternatives such as refactoring the code to allow top level imports should be preferred. Imports that are needed only for type annotations can be placed within an if TYPE_CHECKING: block. Conditionally imported types need to be referenced as strings, to be forward compatible with Python 3.6 where the annotation expressions are actually evaluated. Only entities that are used solely for typing should be defined here; this includes aliases. Otherwise it will be a runtime error, as the module will not be imported at runtime. The block should be right after all the normal imports. There should be no empty lines in the typing imports list. Sort this list as if it were

Write a class that holds the following personal data: name, address, age, and phone number. Store each datum in a field of an appropriate type. (Hint: What is the best type for a variable that stores a phone number? Perhaps counterintuitively, is not a numeric type. Why not?) Write getters and setters for each of your class' fields. Demonstrate your class by writing an application program that creates three instances of it. One instance should hold your information and the other two should hold the information of two of your friends or family members.

Coursehelp Find an online tutor OUR TUTORS STUDENTS Sign in | More QUESTION : Search at blog COURSEHELP FEBRUARY 28, 2019 QUESTION : No Comments Taxpayer Added Substantial Landscaping Golf Course Cost 250 000 Incorrectly Depreciated No Q18171076 . . . Taxpayer added substantial landscaping to its golf course at acost of $250,000. It incorrectly depreciated this non-depreciablecapital cost over a period of five years. What is its adjustedbasis in the landscaping at the end of five years? Explain withreferences to primary sources no guidlines given at all Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Taxpayer Entering Trade Business Operating Burger Franchises Result Incurred 20 000 Legal Q18171034 . . . Taxpayer is entering the trade or business of operating burgerfranchises. As a result, he has incurred $20,000 in legal fees,$15,000 in travel expenses searching for opportunities; $30,000 inemployee training costs prior to opening, and $100,000 in franchisefees. Which costs must be capitalized and how might they beexpensed or amortized? Does your answer change depending on whetherTaxpayer purchases a new franchise or an existing corporation to beheld as a subsidiary? Explain with references to primarysources. Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Tank Containing 900 Liters Liquid Brine Solution Entering Constant Rate 4 Liters Per Minut Q18138424 . . . Please explain thanksA tank, containing 900 liters of liquid, has a brine solution entering at a constant rate of 4 liters per minute. The well-stirred solution leaves the tank at the same rate. The concentration within the tank is monitored and found to be c(t) = e^-t/500/20 kg/L Determine the amount of salt initially present within the tank. Initial amount of salt = Determine the inflow concentration C_in (t), where C_in (t) denotes the concentration of salt in the brine solution flowing into the tank. c_in (t) =Show transcribed image text A tank, containing 900 liters of liquid, has a brine solution entering at a constant rate of 4 liters per minute. The well-stirred solution leaves the tank at the same rate. The concentration within the tank is monitored and found to be c(t) = e^-t/500/20 kg/L Determine the amount of salt initially present within the tank. Initial amount of salt = Determine the inflow concentration C_in (t), where C_in (t) denotes the concentration of salt in the brine solution flowing into the tank. c_in (t) = Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Tank Originally Contains 100 Gal Fresh Water Water Containing 1 2 Lb Salt Per Gallon Poure Q18040998 . . . A tank originally contains 100 gal of fresh water. Then watercontaining 1/2 lb of salt per gallon is poured into the tank at arate of 2 gal/min, and the mixture is allowed to leave at the samerate. After 10 min the process is stopped, and fresh water ispoured into the tank at a rate of 7 gal/min, with the mixture againleaving at the same rate. Find the amount of salt in the tank atthe end of an additional 10 min. (Round your answer to two decimalplaces.) Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Tardex Inc One Class Shares End 2016 Company 30 000 Shares Outstanding Shares Sold 3 Block Q18037518 . . . Tardex Inc. has only one class of shares. At the end of 2016,the company had 30,000 shares outstanding. The shares had been soldin 3 blocks of 10,000 each. The first block was sold at $8 pershare, the second at $9 per share, and the third at $11 per share.Mark Forest acquired 200 shares of the first offering and anadditional 300 shares of the second offering. The total PUC ofMark's shares is equal to: a $4,300 b $4,665 c $4,250 d $5,500 Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Task 3 Need Write 3 Column Cash Book Transaction Done Company November 2007 November 1 Bal Q18069704 . . . Task #3: I need you to Write up a 3 Column Cash Book of the Transactionthat was done with our company (November 2007) November 1 Balance brought forward : Cash in Hand : $100, 000 Cash at Bank : $95,000 November 2 Received Cash loan of $28,000 from Partners. November 3 Bought goods of $59,000 by Check November 4 Bought Motor Van paying by check $2,600 November 5 Cash Withdrawn from the bank $27,000 November 7 Paid Wages in Cash $18,000 November 8 Cash Drawings $14,000 from the Bank November 10 Cash Sales paid directly into the bank $30,000 November 12 We paid the following Accounts by Check less 10%discount in each case: Marshal: $3,000 Linda: $1,800 Theresa: $2,000 November 13 The following paid us their Accounts by check ineach case deducting 2.5% Discount Jerry : $1180 Martins: $550 November 15 Received a further Loan of $3,500 November 16 We paid Brandy his account of $700 by Check November 18 Cash Sales $9,000 November 21 Paid Rent in Cash $1,900 November 23 Received Commission By Check $9,500 November 25 The following persons paid us their Accounts bycheck in each case Deducting 5% Discount: Anthony: $800 David: $6,599 November 26 We paid the following Accounts paid by check in eachcase deducting 2% Discount Joseph: $4000 Thompson: $1,900 November 28: Paid Insurance of $9,900 November 29: Linda paid us a Check for $2,500 having deducted$600 for cash discount. ———————- Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Tax Court Small Case Decision Treated Precedent Cases Explain Partial List Research Aids I Q18104124 . . . Can a Tax Court Small Case Decision be treated as aprecedent for other cases? Explain. Partial list of research aids: IRC Section 7463 (b) Maria Antionette Walton Mitchell, T.C. Summ. 2004-160 Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Systematic Unsystematic Risk Please Give Examples Q18130506 . . . What is systematic and unsystematic risk? Please give examples.Show transcribed image text What is systematic and unsystematic risk? Please give examples. Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments T 14 C Long Must Open Organ Pipe Fundamental Frequency 283 Hz M B Pipe Instead Filled Heli Q18159390 . . . (a) At T = 14°C, how long must an open organ pipe be to have afundamental frequency of 283 Hz?_________ m (b) If this pipe is instead filled with helium at 20°C, what isits fundamental frequency?__________ Hz Expert Answer Attached READ MORE COURSEHELP QUESTION : No Comments Table Need Drawn Need Know Profit Loss Thank Q18042434 . . . The table does not need to be drawn, I just need to know theprofit/loss. Thank you. Today is 04/30/20xy. You have a commodity to sell in a month, and you would like to lock the price at $40 by hedging with futures. Since you are not selling a professionally traded commodity, you take a modified version of futures contract which is marked to the market every week as opposed to every day. The margin account is no- interest-bearing and is not invested on other risk-free securities. The futures price of the commodity you are selling is $42 on 05/01, $39 on 05/08, $41 on 05/15, $37 on 05/22, $39 on 05/29. Assume you enter the contract today and will make the delivery on 05/30, using the 05/29 price. Build a cash flow table of the futures contract on the date listed above (4/30-5/30) in the format of the table shown in class, showing all the calculation details. Show the profit/loss you have made by using the futures contract.Show transcribed image text Today is 04/30/20xy. You have a commodity to sell in a month, and you would like to lock the price at $40 by hedging with futures. Since you are not selling a professionally traded commodity, you take a modified version of futures contract which is marked to the market every week as opposed to every day. The margin account is no- interest-bearing and is not invested on other risk-free securities. The futures price of the commodity you are selling is $42 on 05/01, $39 on 05/08, $41 on 05/15, $37 on 05/22, $39 on 05/29. Assume you enter the contract today and will make the delivery on 05/30, using the 05/29 price. Build a cash flow table of the futures contract on the date listed above (4/30-5/30) in the format of the table shown in class, showing all the calculation details. Show the profit/loss you have made by using the futures contract. Expert Answer Attached READ MORE prev 1 ... 33 34 35 36 37 ... 17,504 next Search for: Do You Have Any Assignment? If you are having any assignment, please feel free to order. Post Assignment Have A New Question? Tip: Ask and we'll first search for similar questions. If there are none, you'll be able to review and add additional details before posting to the community Place your question here:* 0 of 10000000 max characters Attach Files : Drop files here or Enter Number of Pages:* Please enter a value between 1 and 50. Email :* Total $0.00 Submit Join Coursehelp Study For 1 Million+ Textbook Solutions Learn the step-by-step answers to your textbook problems, just enter our Solution Library containing more than 1 Million+ textbooks solutions and help guides from over 1300 courses. 1 24/7 Online Tutors Tune up your concepts by asking our tutors any time around the clock and get prompt responses. CLICK TO START MEMBERSHIP How To Post Question Guided Textbook Solutions Created By Our Experts Learn from step-by-step solutions for over 22,000 ISBNs in Math, Science, Engineering, Business and more 24/7 Study Help Answers in a pinch from experts and subject enthusiasts all semester long Submit Work Submit your work with us and our trained experts will take care of it for you. Make Payment Make payment easily and securely through PayPal. Receive Work Get your work within the deadline without any comprises with the quality. CourseHelp Premium Membership Our Benefits 24/7 Homework Help Quality Help Referencing Pages Correct Formatting 100% Confidential Order Essay COMPANY About Us Contact Us Affiliates HELP & RESOURCES Support Forums Revision Policy POLICY Money Back Policy Terms of Service Privacy Policy CONTACT US 179 Crek, NY 10028. [email protected] Quick Help : [email protected] Coursehelp Coursehelp™ | Assignments solutions - Copyright© 2019 This website uses cookies to enhance your user experience and ensure proper functioning of the website. By continuing to browse this site you are agreeing to our Privacy PolicyAccept and Close

How to cast, and when you would want to do that (and why).

How do you cast in Java? In these situations, you can use a process called casting to convert a value from one type to another. Although casting is reasonably simple, the process is complicated by the fact that Java has both primitive types (such as int, float, and boolean) and object types (String, Point, and the like).

How to initialize a variable.

Initializing a variable. Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

Know how to compare String contents with the String class' equals, equalsIgnoreCase, compareTo, and compareToIgnoreCase methods.

==, equals(), compareTo(), equalsIgnoreCase() and compare() Double equals operator is used to compare two or more than two objects, If they are referring to the same object then return true, otherwise return false. String is immutable in java.

- What a data type is (i.e., what makes up a data type)

A data type is a set of values and a set of operations defined on them. For example, we are familiar with numbers and with operations defined on them such as addition and multiplication. There are eight different built-in types of data in Java, mostly different kinds of numbers. We use the system type for strings of characters so frequently that we also consider it here.

What a return type for a method is.

But methods are set out in a certain way. You have a method header, and a method body. The header is where you tell Java what value type, if any, the method will return (an int value, a double value, a string value, etc). ... The method's return type goes first, which is an int type in the code above.

Know what the logical operators are and how to use them.

LOGICAL OPERATORS IN JAVA RELATED BOOK Java For Dummies Quick Reference By Doug Lowe A logical operator (sometimes called a "Boolean operator") in Java programming is an operator that returns a Boolean result that's based on the Boolean result of one or two other expressions. Sometimes, expressions that use logical operators are called "compound expressions" because the effect of the logical operators is to let you combine two or more condition tests into a single expression. Operator Name Type Description ! Not Unary Returns true if the operand to the right evaluates to false. Returns false if the operand to the right is true. & And Binary Returns true if both of the operands evaluate to true. Both operands are evaluated before the And operator is applied. | Or Binary Returns true if at least one of the operands evaluates to true. Both operands are evaluated before the Or operator is applied. ^ Xor Binary Returns true if one — and only one — of the operands evaluates to true. Returns false if both operands evaluate to true or if both operands evaluate to false. && Conditional And Binary Same as &, but if the operand on the left returns false, it returns false without evaluating the operand on the right. || Conditional Or Binary Same as |, but if the operand on the left returns true, it returns true without evaluating the operand on the right.

What an application program is and how to write one.

How to Write Your First Program in Java Author Info Explore this Article Writing Your First Java Program Hello World Program Input and Output Show 1 more... Questions & Answers Related Articles Java is an object-oriented programming language created in 1995 by James Gosling, which means that it represents concepts as "objects" with "fields" (which are attributes that describe the object) and "methods" (actions that the object can make). Java is a "write once, run anywhere" language, which means that it is designed to run on any platform that has a Java Virtual Machine (JVM). Since Java is a very verbose programming language, it is easy for beginners to learn and understand. This tutorial is an introduction to writing programs in Java.

- How to call a class' instance methods (especially in an application program).

HOW TO CALL instance method in Java? // calling an instance method in the class 'Foo'. Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class. public static void geek(String name) { // code to be executed.... }

What shadowing is, and how to avoid it

Shadowing refers to the practice in Java programming of using two variables with the same name within scopes that overlap. When you do that, the variable with the higher-level scope is hidden because the variable with lower-level scope overrides it. The higher-level variable is then "shadowed."

- What a default constructor is, and when Java provides one.

Java does not initialize any local variable to any default value. So if you are creating an Object of a class it will call default constructor and provide default values to Object. Default constructor provides the default values to the object like 0, null etc. depending on the type.

Write a program that asks the user to enter three integer test scores. The program should display each test score as an integer value, and then the average of the scores. A sample run of your program for the values indicated below should look exactly like this: Please enter first test score: 91 Please enter second test score: 85 Please enter third test score: 87 Your test scores are 91, 85, and 87. Your test average is 87.66666666666667

Search on Programming Puzzles & Code Golf... Log In Sign Up By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute: Sign up Here's how it works: Anybody can ask a question Anybody can answer The best answers are voted up and rise to the top Programming Puzzles & Code Golf Home Questions Tags Users Unanswered I need a program where the user inputs an array of doubles and the program outputs the array sorted Ask Question 280 votes 131 Note: This question was severely edited since I first posted it here. The rules were moved to here, read them before posting any answer to understand the purpose of this. This was the first question created in the code-trolling category. Imagine a lazy user on Stack Overflow asks this question: I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code? How could you create a piece of code that will troll this user? Create a piece of code that will appear useful to an inexperienced programmer but is utterly useless in practice. The winner is the most upvoted answer, except if the answer is somehow not eligible (for eligibility requirements, check the tag wiki description of code-trolling). If the previously most upvoted answer is beaten in the future in the number of upvotes after being accepted, the new best answer is accepted and the previous one is unaccepted. In the case of a tie, I will choose the winner at will among the tied ones or just wait a bit more. Answers that have no code are not eligible. They might be fun and get some upvotes, but they won't be accepted. Rules can be found at tag description. Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information here. code-challenge popularity-contest code-trolling share edited Apr 13 '17 at 12:39 Community♦ 1 asked Dec 27 '13 at 9:17 Victor Stafusa 8,01943259 locked by Doorknob♦ May 10 '14 at 16:09 This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center. Read more about locked posts here. 48 Stack Oversort - ThiefMaster Dec 27 '13 at 13:26 6 @bluesm If someone has already decided to ask someone else to solve their problem instead of "wasting" their own time learning, posting a link to where they can learn on their own isn't going to do any good. - IQAndreas Dec 27 '13 at 16:21 3 Wow, this question's about to get 100 upvotes and 10,000 views in less than 24 hours! - Joe Z. Dec 28 '13 at 1:37 18 My goodness, Victor, your About box is so sad... we all have our ups and downs but you shouldn't beat yourself up man. You're a hero for Code Golfers everywhere now! - SimonT Dec 28 '13 at 4:21 4 I'm surprised no one has offered a solution based on sleep sort yet - Frank Farmer Dec 28 '13 at 11:02 comments disabled on deleted / locked posts / reviews | show 35 more comments 141 Answers active oldest votes 1 2 3 4 5 next 178 votes Sometimes the community here doesn't like to help with homework. That's why you are getting so many joke answers. But I like to help. Here is a complete solution in 'C' (since I assume you want to learn "programming", not "scripting" with Java or Ruby). I've included many tips that I wish I had known when I was first learning #include <stdio.h> //Always use meaningful names for types typedef unsigned char boolean; #define True 't' #define FALSE (!True) //this is a really neat trick for swapping values efficiently void swap(long* a,long *b) { *a=*a^*b;*b=*b^*a;*a=*a^*b; } //Here's a readability improvement #define until(condition) while(!(condition)) int main(int n, char*args[]){ double *d; int i; char input[5]; //should be long enough for most doubles. boolean sorted = FALSE; //In C, you need to specify the array size beforehand, so ask printf("Please enter the length of the array\n"); gets(input); //scan the input string and convert to a value sscanf(input,"%s",&input[0]); n=(long)atol(input); //allocate space, make sure you get the order of arguments right. d = calloc(sizeof(double),n); //Get and sort the array until (sorted) { for (i=0;i<n;i++) { //It's important to always ask nicely printf("Please enter the %d%s array item\n",i,i==1?"st":"th"); scanf("%lf",d+i); } //do a compare and exchange sort: sorted = !sorted; //not sorted //check all the items printf("%d %d\n",i,n); for (i=1;i<n;i++) { //compare if (d[i]<d[i-1]) { //exchange swap(d+i,d+i-1); sorted = FALSE; } } //show results printf("The array is%ssorted\n",sorted?" ":" not "); } //use the --> "downto operator" for counting downto 0. for (;n-->0;) printf("%lf\n",*d++); } share answered Dec 27 '13 at 16:42 AShelly 4,13611531 32 almost all the advice is wrong, and it simply keeps asking for the input list until you enter it already sorted. - AShelly Dec 27 '13 at 16:44 47 +1, for 1st, 2th, 3th, 4th... and the downto operator--very advanced C programing techniques. - Kaya Dec 27 '13 at 17:31 5 Should use sscanf(input, "%5s", &input[0]), otherwise there might be overrun bugs while parsing the input. And input should be declared char input[sizeof(int)+1], for backward compatibility with 64-bit systems. - sh1 Dec 28 '13 at 1:17 12 i==1?"st":"th" hahaha... - Guy Sirton Dec 28 '13 at 7:42 15 Java has garbage collection. Therefore Java is for "scripting", not real programming. That's basic CS101. (so says the troll.) - AShelly Dec 28 '13 at 8:20 show 13 more comments 181 votes Here it is in java. It is utter cheating, unacceptable and unfixable because it creates a MySQL database, insert the number there, do a select with an ORDER BY clause and outputs the numbers given by MySQL. In fact, it is MySQL who is doing the sorting, not the program. package sorter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; public class SortingAlgorithm { private static final String CREATE_DB = "CREATE DATABASE sorting"; private static final String DROP_DB = "DROP DATABASE sorting"; private static final String CREATE_TABLE = "CREATE TABLE sorting.sorting ( num double not null )"; public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); List<Double> doubles = new ArrayList<>(50); String typed; do { typed = JOptionPane.showInputDialog(null, "Type a double:"); if (typed != null) doubles.add(Double.parseDouble(typed)); } while (typed != null); List<Double> sorted = new ArrayList<>(50); try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root")) { try (PreparedStatement ps = con.prepareStatement(CREATE_DB)) { ps.executeUpdate(); } try (PreparedStatement ps = con.prepareStatement(CREATE_TABLE)) { ps.executeUpdate(); } for (Double d : doubles) { try (PreparedStatement ps = con.prepareStatement("INSERT INTO sorting.sorting (num) VALUES (" + d + ")")) { ps.executeUpdate(); } } try ( PreparedStatement ps = con.prepareStatement("SELECT * FROM sorting.sorting ORDER BY num"); ResultSet rs = ps.executeQuery()) { while (rs.next()) { sorted.add(rs.getDouble("num")); } } try (PreparedStatement ps = con.prepareStatement(DROP_DB)) { ps.executeUpdate(); } } JOptionPane.showMessageDialog(null, "The array sorted is: " + sorted); } } share edited Dec 27 '13 at 16:55 answered Dec 27 '13 at 10:40 Victor Stafusa 8,01943259 103 That's actually a little too close to home for what many Java coders would consider an acceptable match of solution to spec!! - Dr. Rebmu Dec 27 '13 at 12:00 10 Also consider the case where you need to sort a very large number of objects. Sorting them "outside the program" in a database is a feasable solution. - Viktor Seifert Dec 27 '13 at 12:44 40 Not enough abstraction here. You need at least 10 interfaces, 20 implementations, enums, unit tests, coverage tests, Maven, integration tests, mocks... - Naftuli Kay Dec 27 '13 at 19:47 6 @NaftuliTzviKay We should create a MySQLSortEnterpriseEdition to implement your idea. Will Victor agree to GPL-license the code here so we can get started? - Joe Z. Dec 27 '13 at 21:32 14 @JoeZ. Yes, my answer is lacking comments about the licensing model and I should make the user accept an EULA in the start of the program. But since I am giving it to the lazy OP, it is free for non-commercial use, including being useful to create the long-awaited premium MySQLSortEnterpriseEdidtion. - Victor Stafusa Dec 27 '13 at 21:39 show 12 more comments 142 votes C# - There's no kill like overkill First of all, dear GiMmEtHaCoDeZ, let's try to break down your task: Read the numbers Sort them Output the sorted numbers. As "Divide and conquer" is very important strategy when working with software problems, lets tackle them one at a time 1. Reading Another important issue in software is versatility. Since it's not specified how the user will input the numbers, that can happen via the console, via a file, via a web service, etc. Maybe even some method that we can't think of at the moment. So, it's important that our solution will be able to accommodate various types of input. The easiest way to achieve that will be to extract the important part to an interface, let's say public interface IDoubleArrayReader { IEnumerable<double> GetDoubles(); DoubleArrayReaderType Type {get;} } where DoubleArrayReaderType is an enumeration given with public enum DoubleArrayReaderType { Console, File, Database, Internet, Cloud, MockService } It's also important to make the software testable from the ground up, so an implementation of the interface will be public class MockServiceDoubleArrayReader : IDoubleArrayReader { IEnumerable<double> IDoubleArrayReader.GetDoubles() { Random r = new Random(); for(int i =0; i<=10; i++) { yield return r.NextDouble(); } } DoubleArrayReaderType IDoubleArrayReader.Type { get { return DoubleArrayReaderType.MockService; } } } Next, the logical question is how we will know to load the appropriate IDoubleArrayReader into the code. That's easy as long as we use a simple factory: public static class DoubleArrayInputOutputFactory { private static Dictionary<DoubleArrayReaderType, IDoubleArrayReader> readers; static DoubleArrayInputOutputFactory() { readers = new Dictionary<DoubleArrayReaderType, IDoubleArrayReader>(); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayReader) { readers.Add((instance as IDoubleArrayReader).Type, (instance as IDoubleArrayReader)); } } catch { continue; } } } public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type) { return readers[type]; } } Note that, we use reflection to load all active readers, so any future extensions will be automatically available Now, in the main body of out code we just do: IDoubleArrayReader reader = DoubleArrayInputOutputFactory .CreateDoubleArrayReader(DoubleArrayReaderType.MockService); var doubles = reader.GetDoubles(); 2. Processing (sorting) Now we need to process, i.e. sort the numbers we have acquired. Note that the steps are completely independent of each other, so to the sorting subsystem, it does not matter how the numbers were inputed. Additionally, the sorting behavior is also something that is subject to change, e.g. we might need to input a more efficient sorting algorithm in place. So, naturally, we'll extract the requested processing behaviour in an interface: public interface IDoubleArrayProcessor { IEnumerable<double> ProcessDoubles(IEnumerable<double> input); DoubleArrayProcessorType Type {get;} } public enum DoubleArrayProcessorType { Sorter, Doubler, Tripler, Quadrupler, Squarer } And the sorting behaviour will just implement the interface: public class SorterDoubleArrayProcessor : IDoubleArrayProcessor { IEnumerable<double> IDoubleArrayProcessor.ProcessDoubles(IEnumerable<double> input) { var output = input.ToArray(); Array.Sort(output); return output; } DoubleArrayProcessorType IDoubleArrayProcessor.Type { get { return DoubleArrayProcessorType.Sorter; } } } Of course, we will need a factory to load and manage the processing instances. public static class DoubleArrayProcessorFactory { private static Dictionary<DoubleArrayProcessorType, IDoubleArrayProcessor> processors; static DoubleArrayProcessorFactory() { processors = new Dictionary<DoubleArrayProcessorType, IDoubleArrayProcessor>(); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayProcessor) { processors.Add((instance as IDoubleArrayProcessor).Type, (instance as IDoubleArrayProcessor)); } } catch { continue; } } } public static IDoubleArrayProcessor CreateDoubleArrayProcessor(DoubleArrayProcessorType type) { return processors[type]; } } 3. Writing the output Nothing much to say here, as this is a process that mirror the input. In fact, we could combine the reading and writing factories into a single DoubleArrayInputOutputFactory, like this: public interface IDoubleArrayWriter { void WriteDoublesArray(IEnumerable<double> doubles); DoubleArrayWriterType Type {get;} } public enum DoubleArrayWriterType { Console, File, Internet, Cloud, MockService, Database } public class ConsoleDoubleArrayWriter : IDoubleArrayWriter { void IDoubleArrayWriter.WriteDoublesArray(IEnumerable<double> doubles) { foreach(double @double in doubles) { Console.WriteLine(@double); } } DoubleArrayWriterType IDoubleArrayWriter.Type { get { return DoubleArrayWriterType.Console; } } } public static class DoubleArrayInputOutputFactory { private static Dictionary<DoubleArrayReaderType, IDoubleArrayReader> readers; private static Dictionary<DoubleArrayWriterType, IDoubleArrayWriter> writers; static DoubleArrayInputOutputFactory() { readers = new Dictionary<DoubleArrayReaderType, IDoubleArrayReader>(); writers = new Dictionary<DoubleArrayWriterType, IDoubleArrayWriter>(); foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayReader) { readers.Add((instance as IDoubleArrayReader).Type, (instance as IDoubleArrayReader)); } } catch { continue; } } foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { try { var instance = Activator.CreateInstance(type); if (instance is IDoubleArrayWriter) { writers.Add((instance as IDoubleArrayWriter).Type, (instance as IDoubleArrayWriter)); } } catch { continue; } } } public static IDoubleArrayReader CreateDoubleArrayReader(DoubleArrayReaderType type) { return readers[type]; } public static IDoubleArrayWriter CreateDoubleArrayWriter(DoubleArrayWriterType type) { return writers[type]; } } Putting it all together Finally, our main program will just use all this awesomeness we have already built, so the code will just be: var doubles = reader.GetDoubles(); doubles = processor.ProcessDoubles(doubles); writer.WriteDoublesArray(doubles); where, e.g. we could define reader, writer and processor using IDoubleArrayReader reader = DoubleArrayInputOutputFactory.CreateDoubleArrayReader(DoubleArrayReaderType.MockService); IDoubleArrayProcessor processor = DoubleArrayProcessorFactory.CreateDoubleArrayProcessor(DoubleArrayProcessorType.Sorter); IDoubleArrayWriter writer = DoubleArrayInputOutputFactory.CreateDoubleArrayWriter(DoubleArrayWriterType.Console); share answered Dec 27 '13 at 21:36 SWeko 1,101166 49 Lol, ListSort Enterprise Edition© :-P +1 - Doorknob♦ Dec 27 '13 at 22:21 14 +1 for crazy overcoding. I suggest you break your answer into 3 or more 'module' answers so that I may +1 them individually - greggo Dec 27 '13 at 23:50 15 And the cherry on top is that it's actually using a library sort:) It's completely to the spec, and completely useless - SWeko Dec 28 '13 at 0:28 9 That... was... beautiful. - Andrew Dec 28 '13 at 6:55 7 Using DI will just confuse the OP, as this is just a quick example. - SWeko Dec 28 '13 at 16:29 show 13 more comments 132 votes Even more literal interpretation: echo " aaehrrty" that is, "the array" sorted. share answered Dec 27 '13 at 20:30 RBerteig 1,139166 5 I came here to post this. - Quuxplusone Dec 28 '13 at 17:08 5 save as file sort.sh and call as sh sort.sh "an array of doubles" - Kyss Tao Dec 28 '13 at 21:29 I think you missed the "the user inputs an array of doubles". - Dukeling Jan 1 '14 at 23:25 1 @Dukeling that's the point of what Kyss Tao's comment. "an array of doubles" can be passed to the script as a command-line argument. - AJMansfield Jan 2 '14 at 21:21 add a comment 108 votes Perl Out of all of the things I've done for CodeGolf.SE, this probably took the most time, at least a few hours. $_[0]=eval<>; for(0..$#{$_[0]}**2){ @_[$#_+1]=[\(@{$_[$#_]}),$#{$_[$#_]}+1]; for(1..$#{$_[$#_]}-$#_){ if(eval('${'x$#_.'@{$_[$#_]}[$_-1]'.'}'x$#_)>eval('${'x$#_.'@{$_[$#_]}[$_]'.'}'x$#_)){ ${$_[$#_]}[$#{$_[$#_]}]=$_; } } (${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]])=(${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]],${$_[$#_]}[${$_[$#_]}[$#{$_[$#_]}]-1]); } for(0..~~@{$_[0]}){ $\.=eval('${'x$#_.'${$_[$#_]}[$_-1]'.'}'x$#_).',' } $\=~s/,*$//;$\=~s/^,*//;$\="[$\]"; print; Input is of the form [2,4,5,7,7,3] and output is of the form [2,3,4,5,7,7]. I don't have time to explain now... be back later. Anyways, there is something called an anonymous array in Perl. It is an array, but it has no name. What we do know, however, is a reference (memory location) that points to it. A series of numbers in square brackets creates an anonymous array, and it returns a reference to it. This answer is built off of a series of anonymous arrays, the references to which are stored in @_. The input is turned into an anonymous array. We then create other anonymous arrays, each element of which is a reference to an element in the previous array. Instead of sorting the elements in the array, we sort the pointers to the elements in that array. Also, we create a new array for each step (and more) in the sort operation. share edited Dec 28 '13 at 13:01 answered Dec 27 '13 at 18:03 PhiNotPi 19.6k967149 3 evil! evil! evil! - DGM Dec 28 '13 at 0:24 56 about as decipherable as any other Perl script to me :) - Corey Goldberg Dec 28 '13 at 0:32 6 @swelljoe Actually, $_ is an empty string at that point. I stored my desired output in $\ , which is the output record separator. - PhiNotPi Dec 28 '13 at 2:58 4 @Andy simple. "How does it work?" - John Dvorak Dec 28 '13 at 18:35 1 and all user-created variables have pretty names that follow all thinkable conventions - Hagen von Eitzen Dec 29 '13 at 13:49 show 4 more comments 80 votes Python Gives the user a sorted array by removing all elements not in sorted order from the input array. import sys sorted = [] for number in map(float, sys.stdin.read().split()): if not sorted or number >= sorted[-1]: sorted.append(number) print sorted The algorithm goes through the list only adding each element if it won't make the list unsorted. Thus the output is a sorted list, just not one that's contains all the elements of the original list. If the op just checks if the list is in sorted order he may not notice that the output is missing values. share edited Dec 28 '13 at 19:43 answered Dec 27 '13 at 16:54 Winston Ewert 1,051610 1 Please see other answers before posting your own. You should add the name of your language. To answer this question you also need to briefly explain what you are doing to troll the OP. - Wasi Dec 27 '13 at 17:14 5 Hehe, this one actually made me laugh out loud. Anyway, I agree that a little better explanation would be helpful. - oconnor0 Dec 28 '13 at 3:49 2 Is the double call to sys.stdin.read() a typo or part of the real trolling-answer? Surely it would frustrate the OP to give the array as input and continue to wait for the result... - Bakuriu Dec 28 '13 at 7:51 Wow, that's evil all right. - Sylverdrag Dec 28 '13 at 14:02 13 A O(n) sort algorithm. Nice. - ejrb Jan 2 '14 at 13:59 show 2 more comments 65 votes Bash, 54 characters A lot of answers using slow inefficient languages like C and Python... let's speed things up a bit by offering a solution in the mother of all scripting languages: Bash. I know what you're thinking - Bash can't even handle floating point arithmetic, so how is it going to sort, right? Well, behold, my implementation of the mighty SleepSort algorithm: #!/bin/bash for i in $@; do echo -n $(sleep $i)$i' '& done echo "Leveraging the power of your $(grep -c ^processor /proc/cpuinfo) cores to \ sort optimally by spawning $(jobs -l | wc -l) concurrent sorting threads..." wait echo -e "\nThe array sorted." The program is provided with input as commandline arguments. Sample run: > ./sleepsort.sh 7 1 4 3 2.752 6.9 0.01 0.02 Leveraging the power of your 4 cores to optimally by spawning 8 concurrent sorting threads... 0.01 0.02 1 2.752 3 4 6.9 7 The array sorted. This also has the advantage of perhaps being the shortest of all working algorithms presented here. That's right - one mighty line of bash, using only bash builtins and not calling any external binaries (that is, if you don't count the purely optional verbose output). Unlike the bogosorts, its runtime is deterministic. Tip: An effective optimisation is to divide the input numbers by a factor before sorting. Implementation is left up to the reader. Edit: Shortened 54-char golf version with less pretty-printing: #!/bin/sh for i in $@;do echo $(sleep $i)$i&done;wait share edited Feb 12 '14 at 18:19 answered Dec 28 '13 at 0:59 Riot 4,60911423 11 Trolling 1: The algorithm does work, but is obviously potentially extremely slow - it spawns a thread for each number, sleeping for that number of seconds before outputting the number (which is thus in order). Trolling 2: Additionally, most of the code is spent on writing a nice comment about how many threads its spawning, and unnecessarily and gratuitously reads and parses the system's cpu info just for the sake of some extra verbose output. Trolling 3: It outputs "the array sorted" at the end, which seems to be the done thing. Trolling 4: The user cannot cancel the "sort" by hitting ctrl-c. - Riot Dec 28 '13 at 1:03 4 5. It only works on GNU/Linux, due to use of /proc/cpuinfo. - kps11346 Dec 28 '13 at 2:37 5 Extremely creative solution, by the way :) - dmitry Dec 28 '13 at 19:37 8 This is amazing. I can't even express how awesome that is. I'm considering using that actively, because WHY NOT. - user11485 Dec 28 '13 at 20:37 4 I actually genuinely do have a variant of this in use in production somewhere. But in that situation, the runtime of the process is important, so that's my excuse... - Riot Dec 28 '13 at 21:01 show 6 more comments 64 votes JavaScript has a built-in sort() function, you can use it like this: var numbers = [6, 2.7, 8]; numbers.sort(); // => [2.7, 6, 8] ...oh, totally forgot to mention, it sorts in lexicographic order, i.e. 10 < 9 and 9 < -100. Probably that's what you expect anyway. share edited Dec 28 '13 at 3:06 answered Dec 28 '13 at 1:42 Alexey Lebedev 74144 8 That's even better because it's a built-in function. - Wayne Werner Dec 29 '13 at 22:52 add a comment 62 votes (jPL) jQuery Programming Language You must use jQuery for that. A simple solution to this problem is the following one: function jSort() { var a = 0.0; // position 1 var b = 0.0; // position 2 var c = 0.0; // position 3 var arr = []; var nArr = []; // don't forget to validate our array! if (window.prompt("You must only type double values. Type 1 if you accept the terms.") != 1) { alert("You can't do that."); return; } for (var i = 0; i < 3; i++) { if (i == 0) { var a = window.prompt("Type a double value"); arr.push(a); } if (i == 1) { var b = window.prompt("Type a double value"); arr.push(b); } if (i == 2) { var c = window.prompt("Type a double value"); arr.push(c); } } // Now the tricky part var b1 = false; var b2 = false; var b3 = false; for (var i = 0 ; i < 3; i++) { // check if the variable value is the same value of the same variable which now is inside the array if (i == 0) { if (a == arr[i]) { b1 = true; } } if (i == 1) { if (b == arr[i]) { b2 = true; } } if (i == 2) { if (c == arr[i]) { b3 = true; } } } if (b1 == true && b2 == true && b3 == true) { if (arr[0] > arr[1]) { if (arr[0] > arr[2]) { nArr.push(arr[0]); } else { nArr.push(arr[2]); } } if (arr[1] > arr[0]) { if (arr[1] > arr[2]) { nArr.push(arr[1]); } else { nArr.push(arr[2]); } } if (arr[2] > arr[0]) { if (arr[2] > arr[1]) { nArr.push(arr[2]); } else { nArr.push(arr[1]); } } console.log(arr.sort(function (a, b) { return a - b })); alert(arr.sort(function (a, b) { return a - b })); } } jSort(); share edited Dec 27 '13 at 17:08 Victor Stafusa 8,01943259 answered Dec 27 '13 at 13:55 Felipe Miosso 71147 72 "-1 not enough jQuery" - grc Dec 27 '13 at 14:18 55 I particularly like how this doesn't actually use jQuery. - KRyan Dec 27 '13 at 15:24 8 -1 Your array naming must include Hungarian notation in it, specifically jQuery objects signified using $, arrays using a and results of window.prompt as p. - Qantas 94 Heavy Dec 27 '13 at 15:48 2 The "tricky part" is elegant. OP, strive to have that kind of code structure someday. - Chris Barker Dec 28 '13 at 8:05 2 That F'n doble "validation" LOOOOOOOOOOOOL omg omg day made! edited for less caps - HC_ Dec 30 '13 at 18:00 show 4 more comments 54 votes C This solution combines the conciseness and OS-level access provided by C with the powerful, reusable software components in GNU/Linux: #include <stdlib.h> main(int argc, char **argv) { system("echo Enter numbers one per line, ending with ctrl-D; sort -g"); } share answered Dec 27 '13 at 21:06 Mark Plotnick 1,221612 4 Or a "script": #!/usr/bin/sort. - Mechanical snail Jan 18 '14 at 4:32 add a comment 54 votes Ruby print "Input an array of doubles: " gets puts "the array sorted." Fairly self-explanatory. Or require the input to actually be "an array of doubles": print "Input an array of doubles: " g = gets until /an array of doubles\n/ puts "the array sorted." Not using gets.chomp for extra evilness. Also using regex after trailing until, which is something I didn't even know you could do (thanks Jan Dvorak) to confuse OP even more! share edited Dec 28 '13 at 18:50 answered Dec 27 '13 at 13:02 Doorknob♦ 54.9k17115352 4 Expanding on the idea, I would repeatedly ask for input until the user inputs the string an array of doubles. - Wrzlprmft Dec 27 '13 at 17:56 @Wrz Ok, done :-) - Doorknob♦ Dec 27 '13 at 17:59 2 That's extra great because the poor OP will have to figure out how to get rid of a newline (because you use gets instead of gets.chomp). - wchargin Dec 27 '13 at 21:17 @WChargin Yep, I had that in the first revision (see revision history) but removed it to be even more evil >:D EDIT: Oh wait, never mind, that was my other answer. I'll edit this one :-) - Doorknob♦ Dec 27 '13 at 21:45 1 +1 I created an account here just to say, this is exactly how I would answer it! Love it! - DGM Dec 28 '13 at 0:10 show 4 more comments 44 votes Python3.3 Sure, here's the most simple Python program that can sort an array given as a list literal on stdin: collections = __import__(dir(object.__subclasses__()[7])[1][4:-3] + chr(116)) URL = ('https://www.google.com/search?client=ubuntu&channel=fs&q=dante+alighieri' '%27s+divina+commedia&ie=utf-8&oe=utf-8#channel=fs&q=__++divina+commedia+' 'dante+alighieri+inferno+__').translate( dict.fromkeys(map(ord, '+-.:,;bcdefghjklopqrstuvwxyz/&=#?%')))[30:] SECRET_KEY = URL[2:10][::-1][3:-1] DATA = '{}{}{}'.format(URL[:2], SECRET_KEY[:2] + SECRET_KEY[:-3:-1], URL[-2:]) if getattr(DATA, dir(list)[7])(__name__): pieces = 'literally - evil'.split(' - ') r = getattr(collections, '_'.join([pieces[0][:-2], pieces[1].translate({ord('j')-1: 'a'})]) )((getattr(globals()['__{}__'.format('buildings'.translate( {100:'t', 103:None}))], 'in' r"put")) ()) tuple((lambda lst: (yield from map(list, map(lambda k: (yield from k), ((lambda i: (yield from map(lambda t: (lst.append(lst[i]) or lst.__setitem__(i, lst[t]) or lst.__setitem__(t, lst.pop())), (j for j in range(i) if (lambda: lst[i] < lst[j])()) )) )(è) for è in range( getattr(lst, dir(lst)[19])())))) ) )(r)) print(r) Unfortunately it works only in python3.3+ since it uses the yield from expression. The code should be quite self-explanatory, so you shouldn't have any problems when handing it in to your professor. The trolling is in providing a perfectly working solution that does exactly what the OP intended, but in a way that is: impossible to understand (by a beginner) impossible to handle in to the teacher because: the OP can't understand it even if he could the teacher wouldn't have time to decipher in order to understand it scary for a naive newbie which might think that programming is too hard for him In summary this answer would greatly increase the frustration of the student mocking their requests with perfectly valid answers from a certain point of view. (Do not read if you consider a challenge understanding the code above) I must add that the trolling is also increased by the fact that the sorting algorithm implemented is actually bubble-sort!... which could surely be implemented in a way that even the OP could understand. It's not an obscure algorithm per se, just a good code-obfuscation of something that the OP could otherwise understand perfectly. share edited Dec 31 '13 at 15:05 answered Dec 27 '13 at 14:23 Bakuriu 771512 3 I think this could use more explanation; what are you doing to the Inferno now? - KRyan Dec 27 '13 at 14:35 1 Wow, you can do non-ascii variable names in python? didn't know... - kratenko Dec 27 '13 at 15:27 1 @kratenko From python3+. In python2 the interpreter assumes ASCII as encoding and would have raised an error. In python3 the interpreter assumes UTF-8 as encoding and accepts all characters that are "letters" by unicode properties for identifiers. - Bakuriu Dec 27 '13 at 15:48 3 @KRyan: He's obviously employing the sorting method that Hell uses to get people into the nine circles. - Joe Z. Dec 27 '13 at 16:18 10 Oh my goodness... +1 for è. - Sean Allred Dec 28 '13 at 2:59 show 3 more comments 41 votes C - Slow, hard to use, unacceptable coding style The sorting algorithm itself is known as slowsort, and has a best case complexity (simplexity) of around n^(log n/2). The algorithm has been published by Andrei Broder and Jorge Stolfi in their great paper "Pessimal Algorithms and Simplexity Analysis" which I highly recommend for good laughs AND food for thought. void sort(double* arr, int n, int i, int j) { if(i < j) { int m = (i+j)/2; sort(arr, n, i , m); sort(arr, n, m+1, n); if(arr[m] > arr[j]) { double t = arr[j]; arr[j] = arr[m]; arr[m] = t; } sort(arr, n, i, j-1); } } However the sorting itself is useless, so we need a way for user to input the data they want to sort. Parsing doubles is pain, so why not input them byte by byte. const unsigned MAX_ELEMS = 100; int main() { int i=0, j=0, len; char a[MAX_ELEMS*8]; double* arr = (double*) a; short isNull=1; while(1) { a[i++] = getchar(); if(i%8 == 0) { if(isNull) break; isNull = 1; } else if(a[i-1] != 0) isNull = 0; } len=i/8 - 1; sort(arr, len-1, 0, len-1); for(i = 0; i < len; i++) { printf("%f ", arr[i]); } } To prove that it works: $ gcc -g trollsort.c -o trollsort trollsort.c: In function 'main': trollsort.c:43:3: warning: incompatible implicit declaration of built-in function 'printf' $ echo -en "\0\0\0\0\0\xe4\x94\x40\0\0\0\0\0\0\xf0\x3f\0\0\0\0\0\0\x45\x40\0\0\0\0\0\0\0\0" | ./trollsort 1.000000 42.000000 1337.000000 In the end we have: The slowest deterministic sorting algorithm I'm aware of Silent hard coded limits on list length Absolutely horrible input, I could also make output similar but I think it's funnier this way. Consider: You will need to know which endianess your machine is to use the program. Also you cannot input 0 (-0 is ok) Pointer arithmetics and pretty much no concern for types as pointers are casted whichever way share edited Dec 30 '13 at 6:32 hippietrail 1068 answered Dec 27 '13 at 17:37 shiona 2,8191122 This has undefined behavior for all inputs greater than 7 bytes. Not an acceptable answer. - Michael Spencer Dec 28 '13 at 3:53 1 Love the "Pessimal Algorithms" paper; thanks. - Ryan Dec 28 '13 at 6:48 "The slowest deterministic sorting algorithm I'm aware of" - the provably slowest deterministic sorting algorithm. That's the whole point of the paper, AFAIR. - Konrad Rudolph Dec 28 '13 at 9:20 @MichaelSpencer Care to elaborate? I gave an example with input size 24 bytes and the output is what one would expect (I think I might be missing a joke here). - shiona Dec 28 '13 at 9:38 2 @Sasho but a bogo-sort has best-case running time of \Omega(n) (n-1 comparisons, 0 operations). That's much faster, aka. worse, than \Omega(n^(log n/2)). - shiona Dec 28 '13 at 10:40 show 4 more comments 39 votes Ruby, evil Bogosort! (Bonus: bogosort by user input) print "Input array of doubles, separated by commas: " arr = gets.split(",") arr.shuffle! until arr.each_cons(2).all? {|x| x[0] < x[1]} puts arr * "," The "evil" twists: runs really really really really really really really slowly, of course uses string comparison, so 10 is less than 2. Can be fixed easily with .map &:to_f appended to the second line, but OP might not know that not using chomp so the last number has a mysterious newline at the end not using strip so there is mysterious whitespace around numbers if input with spacing around commas (ex. The space in 1.5, 2) Or, how about bogosorting by user input?! >:D print "Input array of doubles, separated by commas: " arr = gets.split(",") arr.shuffle! until arr.each_cons(2).all? {|x| print "Is #{x[0]} less than #{x[1]}? (y/n) " gets =~ /y/ } puts arr * "," share edited Dec 27 '13 at 21:56 answered Dec 27 '13 at 13:08 Doorknob♦ 54.9k17115352 Why not bogobogosort? (runs in a quaint O(n * (n!)^n) time) - wchargin Dec 27 '13 at 21:20 @Wchargin I may consider it :-) you may be interested in my recent edit! (Sorry for being slow, I'm actually on my phone right now since I can't access a computer :-P) - Doorknob♦ Dec 27 '13 at 21:57 add a comment 37 votes COBOL Sure! "Even a monkey can do this!" Here is a simple COBOL program that will sort the input for you. Read the comments to see exactly how trivial and extensible it is. The real benefits of this are that it is tried and true mechanism, it does not rely on new and relatively untested languages like Java and anything web-based or from Microsoft. It compiles really effectively, and procedures like this are used by the most successful financial companies in the Fortune500 and other industry leaders. This code has been reviewed by many experts and is recognized as being an excellent mechanism for sorting. 000100 IDENTIFICATION DIVISION. 000200* Cobol sort. Consistent with COBOL 390 000300* does not use sections; does not use go to 000400* uses sort procedures 000500* does a sort with some minimal input validation 000600* since everything is done in an orderly way, 000700* you can easily add code of your own to this program 000800 PROGRAM-ID. 'SORTEX1'. 000900 ENVIRONMENT DIVISION. 001000 CONFIGURATION SECTION. 001100 INPUT-OUTPUT SECTION. 001200 FILE-CONTROL. 001300* INPUT FILE UNSORTED 001400 SELECT UNSORTED-FILE ASSIGN UNSORTED. 001500* The work file for the sort utility 001600* you need the select and an sd but do not need jcl for it 001700 SELECT SORT-WORK ASSIGN SORTWORK. 001800* output file normally a disk/tape file 001900* for this program, send it to the printer 002000 SELECT SORTED-FILE ASSIGN SORTED. 002100* 002200 DATA DIVISION. 002300 FILE SECTION. 002400* 002500 FD UNSORTED-FILE 002600 RECORDING MODE IS F 002900 RECORD CONTAINS 80 CHARACTERS. 003000 003100 01 UNSORTED-RECORD. 003200 05 WS-UR-ACCT-NO PIC X(5). 003300 05 FILLER PIC X(5). 003400 05 WS-UR-AMOUNT PIC 9(5). 003500 05 WS-UR-CUST-NAME PIC X(10). 003600 05 FILLER PIC X(5). 003700 05 WS-UR-TRANS-CODE PIC X(1). 003800 05 FILLER PIC X(49). 003900 004000 SD SORT-WORK 004400 RECORD CONTAINS 80 CHARACTERS. 004500* 004600 01 SORT-WORK-RECORD. 004700* You need a definition and picture for 004800* the field that is sorted on (sort key) 004900 05 SW-ACCT-NO PIC X(05). 005000* YOU NEED A FILLER TO COMPLETE THE DEFINITION 005100 05 FILLER PIC X(75). 005200* 005300 FD SORTED-FILE 005400 RECORDING MODE IS F 005700 RECORD CONTAINS 80 CHARACTERS. 005800* 005900 01 SORTED-RECORD. 006000 05 WS-SR-ACCT-NO PIC X(05). 006100 05 FILLER PIC X(05). 006200 05 WS-SR-AMOUNT PIC 9(05). 006300 05 WS-SR-CUST-NAME PIC X(10). 006400 05 FILLER PIC X(55). 006500 006600 WORKING-STORAGE SECTION. 006700 01 SWITCHES. 006800 05 UNSORTED-FILE-AT-END PIC X VALUE 'N'. 006900 05 SORT-WORK-AT-END PIC X VALUE 'N'. 007000 05 valid-sw PIC X VALUE 'N'. 007100 007200 01 COUNTERS. 007300 05 RELEASED-COUNTER PIC S9(7) 007400 PACKED-DECIMAL VALUE +0. 007500 05 REJECT-COUNTER PIC S9(7) 007600 PACKED-DECIMAL VALUE +0. 007700 007800 PROCEDURE DIVISION. 007900 PERFORM INITIALIZATION 008000* Compare this logic to that of the simple program 008100* notice how the sort verb replaces the 008200* perform main until end of file etc 008300 SORT SORT-work ASCENDING KEY SW-ACCT-NO 008400 INPUT PROCEDURE SORT-INPUT 008500 OUTPUT PROCEDURE SORT-OUTPUT 008600 PERFORM TERMINATION 008700 GOBACK. 008800 008900 INITIALIZATION. 009000* Do what you normally do in initialization 009100* open the regular input file (not the sort work file) 009200* and other files needed 009300* (you could open them in the sort input procedure, too) 009400 OPEN INPUT UNSORTED-FILE 009500 output SORTED-FILE 009600* READ THE FIRST RECORD ON THE REGULAR INPUT FILE 009700 PERFORM READ-IT. 009800* Whatever else you do in initialization 009900* headers, initialize counters, etc 010000 010100 TERMINATION. 010200* Do what you normally do in termination 010300* print out total lines 010400* close the files you opened 010500* display totals 010600 CLOSE UNSORTED-FILE 010700 SORTED-FILE. 010800 010900 READ-IT. 011000 READ UNSORTED-FILE 011100 AT END MOVE 'Y' TO UNSORTED-FILE-AT-END 011200 END-READ. 011300 011400 SORT-INPUT. 011500* This is the 'sort input procedure' 011600* when control passes thru the last statement in it 011700* the input phase of the sort is finished 011800* and actual sorting takes place 011900 PERFORM SORT-INPUT-PROCESS-ALL 012000 UNTIL UNSORTED-FILE-AT-END = 'Y'. 012100 012200 SORT-INPUT-PROCESS-ALL. 012300* This is the point when you have each unsorted input record 012400* in your hands 012500* many programs do some validation or selection here 012600* to determine which records are actually given to the sort util 012700* we will do some simple validation here 012800 MOVE 'Y' TO VALID-SW 012900 PERFORM SORT-INPUT-VALIDATE 013000 IF VALID-SW = 'Y' 013100 THEN 013200** Give the unsorted input record to the sort utility 013300 RELEASE SORT-work-RECord FROM unsorted-RECORD 013400 ADD 1 TO RELEASED-COUNTER 013500 ELSE 013600** Here, you have decided not to give the unsorted input 013700** record to the sort utility 013800 ADD 1 TO REJECT-COUNTER 013900 END-IF 014000 PERFORM READ-IT. 014100 014200 SORT-INPUT-VALIDATE. 014300* Check the regular input record for validity. 014400* if it is not suitable for sorting, set the valid sw 014500* other validation criteria would apply for other files 014600 IF WS-UR-ACCT-NO IS equal to spaces 014700 THEN MOVE 'N' TO VALID-SW 014800 END-IF. 014900 015000 SORT-OUTPUT. 015100* This is the 'sort output procedure' 015200* when control passes thru the last statement in it 015300* the output phase of the sort is finished 015400* you have seen (returned) the last sorted record 015500* and the sort utility is finished 015600 PERFORM RETURN-IT 015700 PERFORM SORT-OUTPUT-PROCESS-ALL 015800 UNTIL SORT-WORK-AT-END = 'Y'. 015900 016000 RETURN-IT. 016100* Gets each sorted record from the sort utility 016200* return is logically like a read 016300 RETURN SORT-work 016400 AT END MOVE 'Y' TO SORT-work-AT-END 016500 END-RETURN. 016600 016700 SORT-OUTPUT-PROCESS-ALL. 016800 PERFORM SORT-OUTPUT-PROCESSING 016900 PERFORM RETURN-IT. 017100 SORT-OUTPUT-PROCESSING. 017200* Here you do the things you do in a 017300* regular program's main processing routine 017400* add totals, compute things 017500* write detail records, print lines, etc 017600* you could put control break check here 017700* this program just and writes the record out to "sorted file" 017900 MOVE SORT-WORK-RECORD TO SORTED-RECORD 018100 WRITE SORTED-RECORD. share edited Apr 13 '17 at 12:39 Community♦ 1 answered Dec 27 '13 at 21:36 rolfl 521413 6 Only you would use COBOL for an answer to this question. +1 - syb0rg Dec 27 '13 at 22:02 5 Ah, the fresh smell of punch cards - Sklivvz Dec 28 '13 at 9:49 3 @EbenezerSklivvze - LOL. I once took out a punched card I was using as a bookmark when my Assembly college professor was telling the class about oldtimey punched cards. He was sufficiently floored (it was in 1994 :). Don't think many of my contemporaries ever saw a whole deck... - DVK Dec 31 '13 at 1:02 add a comment 30 votes OP never said HOW to sort them... or what his definition of doubles is. Assuming datatype double but interpreting it as duplicates. Using JavaScript here. var arr = [4, 6, 7, 4, 5, 9, 11, 7], flag = 1, result = []; while( arr.length ) { for( var i = 0, index = 0; i < arr.length; ++i ) { if( arr[i] * flag < arr[index] * flag ) { console.log(arr[i], arr[index]); index = i; } } arr.splice(index, 1); flag = -flag; } Result: alternating order [4, 11, 4, 9, 5, 7, 6, 7] share edited Dec 27 '13 at 17:26 Victor Stafusa 8,01943259 answered Dec 27 '13 at 13:28 Kiruse 31125 4 "Assuming datatype double but interpreting it as duplicates". Only a truly genius would think that way. Just brilliant! - Felipe Miosso Dec 27 '13 at 15:59 @FelipeMiosso To be honest, I'm not sure if you're just being sarcastic... - Kiruse Dec 27 '13 at 17:26 1 Haha ... I was being sarcastic. I know there are people out there who really think that way. Anyway ... your answer was epic! I laughed a lot. - Felipe Miosso Dec 27 '13 at 17:39 @FelipeMiosso Glad I could help make a laugh. ;) - Kiruse Dec 27 '13 at 20:12 console.log everything! - Emil Vikström Dec 29 '13 at 7:24 show 1 more comment 28 votes PHP Here is a full implementation with error handling. It is the fastest for any array of doubles. <?php function arraySorter($arr) { foreach ($arr as $el) { if ($el != 'double') { throw new Exception('Unexpected Error: Invalid array!'); } } return $arr; } $arrayOfDoubles = Array('double', 'double', 'double', 'double', 'double'); var_dump(arraySorter($arrayOfDoubles)); ?> share answered Dec 27 '13 at 18:30 totymedli 36158 add a comment 25 votes do { } while(next_permutation(begin(ar), end(ar))); Next permutation in C++ works by returning true when the array is sorted and false otherwise (after it permutes). So you are supposed to sort the array and then use it in a do-while as above (so it will make a full circle back to the sorted array). share answered Dec 27 '13 at 18:15 user974006 34923 +1 I thought about using next_permutation for my answer, but this is a lot cleaner than what I had in mind. - jliv902 Jan 6 '14 at 14:39 add a comment 25 votes [solution by punctilious misdirection] Please read the relevant standard, IEC 60559:1989 Specification for binary floating point arithmetic for microprocessor systems, which you can purchase here. In the footnote to §5.10 Details of totalOrder predicate, it is noted that: totalOrder does not impose a total ordering on all encodings in a format. In particular, it does not distinguish among different encodings of the same floating-point representation, as when one or both encodings are non-canonical. Thus we see that it is impossible to write code to sort doubles. It is a trick question. Ha, ha, very clever! Please tell your professor I am enjoying his course very much. [edit: nothing requires me not to assume that the problem demands a total order] share edited Dec 27 '13 at 20:42 answered Dec 27 '13 at 17:42 kps11346 18114 3 But the problem was to sort the doubles. Nobody required the values to be in (total)order. For example you could sort the array into two, positive and negative numbers. You were doubletricked by the question. - shiona Dec 27 '13 at 18:10 add a comment 23 votes An evil JavaScript: OP, I don't want to give you everything so I'll let you figure out how to get input from the user on your own (hint: use prompt). Once you have that, here is a function you can pass your array into to sort it. You just need to provide the array, the lowest value in the array, and an increment: var sortDoubles = function (unsortedArray, minimumVal, increment) { var sortedArray = []; while (unsortedArray.length != sortedArray.length) { var index = unsortedArray.indexOf(minimumVal); if (index != -1) { sortedArray.push(unsortedArray[index]); } minimumVal += increment; } return sortedArray; }; Here is a fiddle to see it in action with the example user input [1.5, -3.5, 12, 10, -19.5]. Note: Aside from being poor-performing, complex, and unextensible for the problem at hand, this will be especially frustrating if the OP doesn't know about floating point math. For example, if the user input is [8.1, 5, -.8, 2.3, 5.6, 17.9] and the OP chooses the straightforward values (i.e. minimumVal=-.8 and increment=.1), the program will run forever. On a related note, I am currently the proud owner of 2 non-functioning browser tabs due to this very issue :) Note II: I felt disgusting even writing the above code. Note III: MWA HAHAHAHA! share answered Dec 27 '13 at 17:19 Briguy37 2,296923 Nice idea. You must have been cool when you were still a programming newbie. - Pierre Arlaud Jan 2 '14 at 13:47 add a comment 22 votes Here is an actual answer that I like for Java: Add the Line before println and your array gets sorted Arrays.sort( array ); No explanation, confuses the OP, but works and will get upvotes from more experienced programmers. Another similar answer: Take a look at Arrays.sort() Indirectly telling the OP to do his own research while giving him a vague correct answer. Without further research, the OP is still confused. I also like that the link points to older documentation. share edited May 23 '17 at 12:41 Community♦ 1 answered Dec 27 '13 at 18:13 syb0rg 990623 10 This is useful and thus worthy of a down-vote. - emory Dec 27 '13 at 20:13 11 "Indirectly telling the OP to do his own research while giving him a vague correct answer" pretty much describes my style of StackOverflow answering :/ - Corey Goldberg Dec 28 '13 at 0:37 7 "Take a look at Arrays.sort()" ... "Could I get an example how to use it in my program?" ... brilliant. - SimonT Dec 28 '13 at 4:14 5 +1 especially because our humble OP probably needs to write a sort him/herself for a class, making Array.sort() completely useless to him/her. - Kevin Dec 28 '13 at 7:25 2 Ctrl + F -> "Could I get an example how to use it in my program?" = 3 results. - Qix Dec 30 '13 at 3:17 show 5 more comments 21 votes Genetic algorithm/Monte Carlo method for the sorting problem in JAVA The sorting problem is known to computing science for a long time and many good solutions have been found. In recent years there have been great advances in biocomputing and looking at how biology solves problems has shown to be of great help in solving hard problems. This sorting algorithm takes the best of these ideas to use them to solve the sorting problem. The idea is pretty simple. You start with an unordered array and find out how sorted this is already. You give it a score of its "sortedness" and then permute the array with a random component - just like in biology where it is not clear how the kids will look like even if you know all about the parents! This is the genetic algorithm part. You create the offspring of that array so to say. Then you see if the offspring is better sorted than the parent (aka survival of the fittest!). If this is the case you go on with this new array as starting point to build the next permutation and so forth until the array is fully sorted. The cool thing about this approach is that it takes shorter, if the array is already a bit sorted from the start! package testing; import java.awt.List; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Random; import org.joda.time.DateTime; import org.joda.time.Interval; public class MonteCarloSort { private static final Random RANDOM = new Random(); public static void main(String[] args) { List doubleList = new java.awt.List(); // prompt the user to enter numbers System.out.print("Enter a number or hit return to start sorting them!"); // open up standard input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = null; // read the numbers from the command-line; need to use try/catch !!! do{ try { input = br.readLine(); } catch (IOException ioe) { System.out.println("IO error trying to read a number!"); System.exit(1); } try { double d = Double.parseDouble(input); doubleList.add(input); } catch (NumberFormatException e) { if (!input.equals("")) System.out.println("Only numbers are allowed."); } } while (!input.equals("")); printCurrentListAndStuff(doubleList); while (isAscSorted(doubleList) < doubleList.getItemCount()){ List newlist = createPermutation(doubleList); //genetic algorithm approach! if (isAscSorted(doubleList) <= isAscSorted(newlist)){ //the new list is better, so we use it as starting point for the next iteration! doubleList = newlist; printCurrentListAndStuff(doubleList); } } System.out.println("done!"); } private static void printCurrentListAndStuff(List doubleList){ System.out.print("array sortedness is now " + isAscSorted(doubleList) + "(max = "+doubleList.getItemCount()+"): "); printList(doubleList); System.out.print("\n"); } private static void printList(List doubleList){ for (int i = 0; i < doubleList.getItemCount(); i++){ String doubleVal = doubleList.getItem(i); System.out.print((i>0?", ":"") +doubleVal); } } private static List createPermutation(List doubleList){ int sortedness = isAscSorted(doubleList); if (sortedness == doubleList.getItemCount()) return doubleList; //we take the first non fitting item and exchange it by random int swapWith = RANDOM.nextInt(doubleList.getItemCount()); //it makes no sense to swap with itself, so we exclude this while (swapWith == sortedness){ swapWith = RANDOM.nextInt(doubleList.getItemCount()); } List newList = new List(); for (int i = 0; i < doubleList.getItemCount(); i++){ if ( i == sortedness){ newList.add(doubleList.getItem(swapWith)); } else if ( i == swapWith){ newList.add(doubleList.getItem(sortedness)); } else{ newList.add(doubleList.getItem(i)); } } return newList; } /** * A clever method to get the "degree of sortedness" form a given array. the * bigger the number the more sorted it is. The given list is fully sorted if * the return value is the length of the list! * * @param doubleList * @return a number */ private static int isAscSorted(List doubleList){ double current = Double.NEGATIVE_INFINITY; for (int i = 0; i < doubleList.getItemCount(); i++){ String doubleVal = doubleList.getItem(i); if (Double.parseDouble(doubleVal) >= current){ current = Double.parseDouble(doubleVal); } else{ return i; } } return doubleList.getItemCount(); } } Extras Misuse of java.awt.List inconsistent and bad variable naming completely bullshit blah blah about biocomputing inventive and inconsistent language in the explanation monte carlo is plainly the wrong tool for straight forward deterministic problems unneeded imports probably more goodies... share edited Dec 27 '13 at 23:11 Victor Stafusa 8,01943259 answered Dec 27 '13 at 20:04 luksch 32127 Is calling this GA or Monte Carlo another level of troll? I believe this is a randomized hill-climbing algorithm. - shiona Dec 27 '13 at 20:17 associating this program with buzzword names was intentional, but I never heard of "randomized hill-climbing algorithm" either... and in a broader sense I think GA and Monte Carlo are not too far off to be plainly wrong... - luksch Dec 27 '13 at 20:25 add a comment 19 votes Python a = map(float, raw_input().split()) print sorted(a, key=lambda x: int(x * 10**3) % 10 + int(x * 10**5) % 10) Sorts the array (list) by the sum of the 3rd and 5th decimal places. share answered Dec 27 '13 at 13:31 grc 18.2k93076 5 Unfortunately, this is trivially fixed by removing everything after lambda x: and replacing it with x. Still, a beginner coder would never know that, so kudos! - Joe Z. Dec 27 '13 at 15:54 add a comment 18 votes C++ This works... eventually. Here's my sorting algorithm: template <typename Iterator> void sort (Iterator first, Iterator last) { while (std::is_sorted (first, last) == false) { std::shuffle (first, last, std::random_device()) ; } } Here's the full program: #include <algorithm> #include <iostream> #include <random> #include <string> #include <sstream> #include <vector> namespace professional { template <typename Iterator> void sort (Iterator first, Iterator last) ; } // end of namespace professional std::vector <double> get_doubles () ; int main (void) { std::vector <double> vecVals = get_doubles () ; professional::sort (std::begin (vecVals), std::end (vecVals)) ; for (const double d : vecVals) { std::cout << d << " " ; } std::cout << std::endl ; return 0 ; } template <typename Iterator> void professional::sort (Iterator first, Iterator last) { while (std::is_sorted (first, last) == false) { std::shuffle (first, last, std::random_device()) ; } } std::vector <double> get_doubles () { std::cout << "Please enter some space delimited doubles." << std::endl ; std::vector <double> vecVals ; std::string strLine ; std::getline (std::cin, strLine) ; std::stringstream ss (strLine) ; while (1) { double d = 0 ; ss >> d ; if (ss.bad () == false && ss.fail () == false) { vecVals.push_back (d) ; } else { break ; } } return vecVals ; } share edited Dec 27 '13 at 16:21 answered Dec 27 '13 at 15:40 jliv902 22115 6 Your sort "algorithm" had me in tears. - Nate Dec 27 '13 at 22:42 Hah, that is not an algorithm because it is not granted to finish >:D - jmacedo Dec 31 '13 at 5:50 @joxnas, actually on systems where non-deterministic random devices are not available, the randomizer may actually be periodic. Then it would simply depend on whether the set of possible permutations allowed by the randomizer subsumes the set of possible permutations $S_n$ for all possible input array lengths $n$. - bug Dec 31 '13 at 19:16 Aw pants, I forgot LaTeX was only supported on TeX.SE and Math.SE. Just imagine those symbols in snooty italix. - bug Dec 31 '13 at 19:18 add a comment 18 votes Here, feast your eyes: <?php if (isset($_POST["doubleArray"]) === true) { $doubleValues = explode(":", $_POST["doubleArray"]); if (is_numeric($_POST["smallestDouble"])) { $sorted = $_POST["sorted"] . ":" . $doubleValues[$_POST["smallestDouble"]]; unset($doubleValues[$_POST["smallestDouble"]]); $doubleValues = array_values($doubleValues); } if (count($doubleValues) > 0) { $i = 0; foreach ($doubleValues as $value) { echo $i . " : " . $value . "<br />"; $i++; } echo "Type the index of the smallest double value in the list: "; } else { echo "Sorted values" . $sorted; } }else { echo "Enter double values separated by a colon (:)"; } ?> <form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" > <?php if (!isset($doubleValues)) { echo '<input type="text" name="doubleArray" /><br>'; } else { echo '<input type="hidden" name="doubleArray" value="' . implode(":", $doubleValues) . '" ><input type="text" name="smallestDouble" /><br>'. '<input type="hidden" name="sorted" value="' . $sorted . '" >'; } ?> <input type="submit" value="Submit"> </form> This piece of code displays the array and asks the user to enter the smallest double of the array. It then adds the number to the list of sorted numbers, removes the double from the array and display the remaining array numbers. * Misinterpreting: Weak point, but the OP is not exactly expecting the program to ask the user to help sorting. * Cheating: the user is the one doing the actual sorting. * Performance: Every number of the array requires a server roundtrip, and it requires the user to find the smallest number manually. Performance can't get much worse. * Unacceptable: I think I got that covered. And good luck on reusing it. Worst comes to worst, the user could get rid of 90% of the code and loop through repetitively to find the smallest values and removing them each time, which would give him one of the least efficient sorting algorithms. * Creative and evil: you tell me. share answered Dec 27 '13 at 19:32 Sylverdrag 1813 2 You say 'feast your eyes' and give me PHP O.o - Aidiakapi Dec 28 '13 at 19:53 3 "Evil" was part of the requirements, wasn't it? - Sylverdrag Dec 29 '13 at 10:26 add a comment 17 votes Javascript Intelligent Design Sort function sort(array){ console.log("Someone more intelligent than you has already sorted this optimally. Your puny brain cannot comprehend it"); return array;//I do believe that this is the fastest sorting algorithm there is! } share answered Dec 27 '13 at 14:27 scrblnrd3 1,3501918 6 Credit where credit is due: dangermouse.net/esoteric/intelligentdesignsort.html - wchargin Dec 27 '13 at 21:21 1 Don't understand why you bash intelligent design in a programming contest? - khebbie Dec 28 '13 at 8:00 12 @khebbie Why not? - Konrad Rudolph Dec 28 '13 at 9:19 Problem is, if the user is the one who input the numbers, then they would be more intelligent than themselves. ;) - d-_-b Jan 1 '14 at 3:27 add a comment 16 votes Python - req. #1 This code will sort the doubles in lexicographical order rather than increasing numerical order, by creating a prefix tree of digits and then iterating through them recursively. class trie_node: def __init__(self): self.chn = {} self.instances = 0 for char in "0123456789.-+e": self.chn[char] = None def insert_number(self, number): if(number == ""): self.instances += 1 else: self.chn[number[0]] = trie_node() self.chn[number[0]].insert_number(number[1:]) def get_sorted_array(node, number): array_to_return = [number] * node.instances for char in "0123456789.-+e": if node.chn[char] != None: array_to_return += get_sorted_array(node.chn[char], number + char) return array_to_return def pcg_sort(arr): root = trie_node() for element in arr: root.insert_number(str(element)) sarr = get_sorted_array(root, "") fsarr = [] for element in sarr: fsarr.append(float(element)) return fsarr input_array = [] while True: number = raw_input("Enter a double (/ to end): ") if(number == "/"): print pcg_sort(input_array) break else: try: number = float(number) input_array.append(number) except ValueError: pass It works in n log n time, and is in fact a smart way to keep a sorted list otherwise, but unfortunately for the OP, it does completely the wrong thing. share edited Dec 27 '13 at 17:15 Victor Stafusa 8,01943259 answered Dec 27 '13 at 15:52 Joe Z. 17.2k1246118 4 It's also particularly devious in that if all the numbers have the same number of digits before the decimal point, it will actually work correctly, so the OP might not even notice that the sort is doing something wrong if he just tests it using an input of, say, 2, 1, 3, 8, 5. - Joe Z. Dec 27 '13 at 15:59 add a comment 14 votes Sorts the array of doubles. In Java: public String sort(double[] input){ String s = ""; for(Double d:input){ s+=Long.toBinaryString(Double.doubleToRawLongBits(d)); } char[] chars=s.toCharArray(); Arrays.sort(chars); s=""; for(char c:chars){ s+=c; } return s;} For instance: [0.0, 1.5, 123] goes from the unsorted binary representation of 011111111111000000000000000000000000000000000000000000000000000100000001011110110000000000000000000000000000000000000000000000 to the elegantly sorted 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111 share edited Feb 27 '14 at 4:52 Justin 17.8k953108 answered Dec 27 '13 at 23:39 planetguy32 41126 add a comment 11 votes I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code? Edit per @kealist, I guess it is better if commented to make the divide seem plausible. In Rebol... doubled-list: load ask "Input list of doubles: " ;-- The list is of doubles, so we have to undouble them before sorting ;-- Use MAP-EACH to create a new list with each element divided by two undoubled-list: map-each num doubled-list [num / 2] ;-- Note: We could also have sorted before we undoubled the numbers print sort undoubled-list Playing off the idea that they don't actually know what a double is, and might believe a list of doubles were just a bunch of numbers multiplied by two. share edited Dec 28 '13 at 13:15 answered Dec 27 '13 at 12:07 Dr. Rebmu 1,9121131 6 Maybe they need to be halved since the input is already doubled! - kealist Dec 27 '13 at 15:13 @kealist I considered that, however this plays on the idea that "doubling" is taking place. I think it sneaks by a little better to have the [2 * num]. - Dr. Rebmu Dec 27 '13 at 15:20 add a comment 10 votes Deliberately misunderstanding the question: Using a recursive approach: def recsort(array): "Recursive sort" if array: for j, i in enumerate(array): for l1 in recsort(array[:j]): for l2 in recsort(array[j+1:]): yield i + l1 + l2 yield i + l2 + l1 else: yield '' for p in recsort(raw_input("Array:")): print p The sorted array is guaranteed to be outputed at some point, for any type of data in the array, even any kind of sorting order, and even any kind of separator for the input, which makes this approach extremely flexible. Its main drawback is that it is a bit slow for large arrays, but you can solve that easily with multithreading. share edited Dec 27 '13 at 15:15 answered Dec 27 '13 at 12:58 Valentin CLEMENT 32115 add a comment 1 2 3 4 5 next Not the answer you're looking for? Browse other questions tagged code-challenge popularity-contest code-trolling or ask your own question. asked 5 years, 2 months ago viewed 433,125 times active 5 years ago 125 people chatting Primes and Squares 49 mins ago - El'endia Starman El'endia Starman: 49 mins ago DJMcMayhem: 49 mins ago flawr: 1 hour ago PhiNotPi: 7 hours ago Laikoni: Aug 16 at 10:57 talk.tryitonline.net 2 hours ago - Conor O'Brien Dennis: 8 hours ago Adám: 13 hours ago Sara J: yesterday Jeff Zeitlin: Jan 29 at 10:57 caird coinheringaahing: Jan 5 at 8:25 Phlarx: Dec 7 at 11:30 Laikoni: Nov 10 at 9:12 Linked 101 Execute prints backwards 53 Is this even or odd? 51 "Creative" ways to determine if an array is sorted 42 How do I write an adding function? 33 How do I find the longest palindrome in a string? Related 6 Build a snowman! 33 How do I find the longest palindrome in a string? 16 Generate a random sequence of numbers 13 Input text from one file, output it to another 42 How do I write an adding function? 21 How do I split a string??? Help plz? (code trolling) 18 How do I find the factorial of a positive number? 10 How do I convert a word document to a pdf? 68 How to write a C program for multiplication without using the * and + operators? 13 Break some standards! Hot Network Questions How can animals be objects of ethics without being subjects as well? What are "industrial chops"? Why did the villain in the first Men in Black movie care about Earth's Cockroaches? How long is the D&D Starter Set campaign? Math Saturation Symbol Why avoid shared user accounts? Explain the objections to these measures against human trafficking Can we use the stored gravitational potential energy of a building to produce power? How to prevent cleaner from hanging my lock screen in Ubuntu 16.04 Why is the copy constructor called twice in this code snippet? awk + sum all numbers Is it a fallacy if someone claims they need an explanation for every word of your argument to the point where they don't understand common terms? What is 6÷2×(1+2) =? Making him into a bully (how to show mild violence) Why are the books in the Game of Thrones citadel library shelved spine inwards? Publishing research using outdated methods Why do

How to use a combined assignment operator

Variables and Combined Assignment Operators You'll commonly want to complete a math function and assign the resulting value back to some named object, called a variable. ActionScript makes this easier by letting you combine arithmetic and assignment operators together. Take a look at an assignment operator example: Create a new ActionScript 3.0 project and enter in the following code for the project: // Assignment Operators var myValue:Number = 2; myValue = myValue + 2; trace(myValue); var myOtherValue:Number = 2; myOtherValue += 2; trace(myOtherValue); Run the project. You'll get the following in the Output panel: 4 4 Let's walk through the code and explain how you get this result and what role variables and combined assignment operators play. Variables You haven't really seen much about the var statement yet, so let's reveal a little bit more about it. You have used it in the past to create named object containers that you have then assigned MovieClip symbols to using the new statement. You can also use var to create variables; in fact, variables is what var stands for. Variables are named objects that can contain variable values. Take a look at the second line of the assignment operators example: var myValue:Number = 2; The var statement is creating a variable called myValue. See that :Number after the variable name? You have to tell ActionScript what type of data your variable can hold, similar to how you did when using the function statement. In this case, you are saying that myValue will contain a number. When you create the variable, it is empty, but when you assign the numeric value 2 to it, you can refer to that value using the name myValue. myValue = myValue + 2; trace(myValue); On the second line above, you are accessing the myValue object and are assigning a new value to it. Notice that you are not using the var statement here, because var is only used to create a new variable. You don't need to use it again if you are referring to a variable that has already been created. Before you assign the value, you need to complete the evaluation on the right side of the assignment operator. In this case, you are taking the existing value of myValue, 2, and adding the value 2 to it. This value is then assigned back to myValue, overwriting the existing value. In the last line of the first block, you send that value to the Output panel using the trace statement, which displays 4. This completes the analysis of the first part of the code. Combined Assignment Operators Take a look at the second block of code. This section of code works identically to the first block, with two exceptions. In this section, you are creating a new variable called myOtherValue: var myOtherValue:Number = 2; myOtherValue += 2; trace(myOtherValue); In the first line, you need to use the var statement since you have not created that variable before. You then assign the numeric value 2 to it. On the next line, you come across the first combined assignment operator, +=. This operator is combining addition with assignment. In this case it is taking the existing value of myOtherValue and is adding 2 to it and automatically assigning it back to the myOtherValue variable. Always put the arithmetic operator before the assignment operator. You can use this shortcut with any of the basic arithmetic operators: // All combined assignment operators var myValue:Number = 100; myValue += 50; // 100+50 = 150 myValue -= 125 // 150-125 = 25 myValue *= 3 // 25*3 = 75 myValue /= 5 // 75/5 = 15 myValue %= 4 // 15%4 = 3 trace (myValue); Programmers often use these combined assignment operators as shortcuts since they are nice time savers. Hopefully, you'll find they are too!

what is an instance of a class

Instance variable in java is used by Objects to store their states. Variables which are defined without the STATIC keyword and are Outside any method declaration are Object specific and are known as instance variables. They are called so because their values are instance specific and are not shared among instances

How to use String.format to nicely format strings.

The most common way of formatting a string in java is using String.format(). If there were a "java sprintf" then this would be it. String output = String.format("%s = %d", "joe", 35); For formatted console output, you can use printf() or the format() method of System.out and System.err PrintStreams.

- How to provide (only) what is asked for in a problem. This way that I will know that you know what has been asked. For example, if I ask for an initialization, do not give a declaration and an assignment statement, or I will think you do not know the difference between a declaration, and assignment, and an initialization. Similarly, if I ask for an if-statement involving an integer variable x in some way, then do not also include a declaration of x in your solution, or I will think that you do not know the difference between a variable declaration and an if-statement. Or if I ask for a boolean expression, then do not embed it in a conditional statement or I will think you do not know the difference between an expression and a statement.

Writing Classes and Javadoc Advanced Programming/Practicum 15-200 Introduction We have already learned a lot about using classes from prewritten libraries and about reading their Javadoc to understand them. In this lecture, we will discuss the form and meaning of writing Java classes and Javadoc. So, we will examine the same language features that that we have already used, but now from the perspective of writing classes. The discussion starts by investigating methods in general. We will discuss how to write static methods first programs (and learn about the special main method in an application program) and then in simple library classes (such as Math and Prompt which programs can import) . We will learn about call frames: pictures that illustrate the universal parameter passing mechanism in Java: copy by value. We will also learn how to write methods that throw exceptions, if they are called with objects/arguments that do not meet their preconditions. Finally, we will learn how to write more interesting classes, focusing on declaring fields (mostly instance variables) and using them when writing constructors and methods. During this process, we will see how to use various features in the the Eclipse IDE (edit view and debug perspective) that facilitate the analyzing, writing, and debugging of classes. Method Definitions and Parameter Initialization Let's start our discussing by examining a simple method that defines the min method inside the Math class. It illustrates most interesting aspects of static method definitions. Before reading this code, quickly scan the EBNF for method-definition. public static int min (int a, int b) { if (a <= b) return a; else return b; } We divide method definitions into two parts: the header and the body. The method header comprises the access modifiers (public static), return type (int), method name (min), and parameters (int a, int b); if this method threw any exceptions, they would appear next. We should be very familiar with reading method headers in Javadoc from a previous lecture. The method body is a block-statement that immediately follows the method header. In this lecture we will focus our attention on writing this block. Its statements use the parameter names just like variable names; in fact, we often call them parameter variables to make this similarity explicit. We have already discussed that when a method is called, its parameter variables are always initialized by their matching arguments first. Then, the method body executes, using these values to compute and return its result; it can also any local variables declard in the block to help in its computation. If we wrote the statement System.out.println( Math.min(3,5) ); it would display 3. If we had declared int x = 3, y = 8; and wrote the statement System.out.println(Math.min (3*x+5,y) ); it would display 8 Generally, We call a method by writing its name, followed in parentheses by its arguments (one for each parameter in the method's header) As in the header (where parameters are separated by commas), arguments are are separated by commas as well. When we call a method, Java first evaluates each argument (each can be a simple or complicated expression) and transmits or passes it to its matching parameter; this just means that Java uses each argument's value to initialize it matching parameter in the method. It is equivalent to writing first-parameter = first-argument, then second-parameter = second-argument, etc. Thus, when calling Math.max(3*x+5,y) above, the first parameter (a) is initialized by the value 14 (3*x+5: the equivalent of a = 3*x+5). Likewise, the second parameter (b) is initialized by the value 8 (y: the equivalent of b = y). Then, Java executes the body of the method, which typically performs some computation using these initialized parameters. It finally returns a result, by a mechanism that we discuss in the next section. The return Statement We will now discuss another Java statement, the return-statement, whose EBNF is simply stated (return is a keyword) as return-statement <= return [expression]; As a syntax constraint, Java requires that expression must be compatible with the return-type specified in the method's header (either be the same, or be implicitily convertible). In a void method (or a constructor), Java requires us to discard this option altogether. Typically, expression is a literal or a variable, but sometimes it is a more general expression using operators/method calls. For example, we will see methods that include the return statements return true; return a; return i%divisor==0; We use a return statement to terminate a method and specify what result (if any) it should return Whenever a method executes return, no matter what else it is is doing (i.e., inside loops or try-catch or ...), the method immediately terminates and returns to where the method was called (its call site). If the method returns a value, it is as if the method call is "replaced" by the value that it returns as a result. Ideally, a method should contain just one return statement, at its end. In fact, we can prove mathematically that there is always a way to write a method with one return statement. But sometimes methods are easier to understand if they have multiple return statements. Thus, we will adopt a more pragmatic approach, putting simplicity as the paramount aspect of the code that we write: if multiple return statements make a method simpler and easier to understand, use them. But be able to argue why; don't just use them because you are sloppy. I would argue, for example, that the min method defined above, which has two return statements, is simpler than the one below, which has only one return statement. public static int min (int a, int b) { int answer; if (a <= b) answer = a; else answer = b; return answer; } Instead of one if statement, this method's body is a sequence of three statements that declare a local variable, decide how to initialize it, and then return that value. The original method just chose which of its parameters to returns, without declaring any local variable. I think that the original method is simpler and easier to understand. In fact, this method is actually defined in the Java library as public static int min (int a, int b) {return (a <= b ? a : b);} Sample Methods The following method definitions compute useful and interesting values. In practice, many useful methods are short, like these; study their headers and especially their bodies. public static boolean isLeapyear (int year) {return (year%4 == 0 && year%100 != 0) || year%400 == 0;} This method hides a very messy calculation inside a well-named and easy to call method: it just has one parameter: the year to do the calculation on. public static boolean isBetween(int low, int middle, int high) {return low<=middle && middle<=high;} This method captures a common pattern that we have explored before (and why low <= middle <= high does not correctly compute the required value). The correct way to perform this test is a bit verbose, so calling this method can simplify our code. public static double distance (double x1, double y1, double x2, double y2) {return Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );} This method computes the simple Euclidean distance between two points, which must be specified as four parameters: the X- and Y-coordinate of each point (although a better method would use two parameters, each an instance of a Point class, to represent these four values). Some methods have quite a few parameters (see below for even more). public static boolean inCircle (double centerX, double centerY, double centerRadius, double pointX, double pointY) {return distance(centerX,centerY,pointX,pointY) <= centerRadius;} This method calls distance to compute whether a point (whose coordinates are pointX and pointY) falls within a circle (whose center's coordinates are centerX and centerY, and whose radius is centerRadius). Note that four of the coordinate parameters to inCircle become arguments to the call of distance; this role switch is common in methods calling other methods. By layering methods on top of methods, each is kept small, but each new method accomplishes much more than the methods it calls, by building on it; this layer mechanism enables power programming. public static int factorial (int n) { int answer = 1; for (int i=2; i<=n; i++) answer *= i; return answer; } This method is interesting because it declares two local variables (answer and i; methods can declare and use local variables along with their parameters), one of which is finally returned. When writing methods, beginners sometimes have difficulty determining when to declare parameter variables and when to declare local variables. Here is where thinking about prototypes helps: any information that must be communicated to the method by arguments must be stored in a parameter variable; local variables help in the computation, but do not need to be initialized by arguments: we need n to specify the factorial we are computing, but answer is always initialized to 1 and i is always initialized to 2 in the for loop. Methods should have the fewest number of parameters possible; if a variable can be declared locally, it should be. public static int forInt (String message) { for (;;) try { return Integer.parseInt(Prompt.forString(message)); } catch (NumberFormatException nfe) {System.out.println("Enter an int please");} } public static int forInt (String message, int low, int high) { for (;;) { int answer = Prompt.forInt(message + "[" + low + ".." + high + "]"); if ( Utility.isBetween(low, answer, high) ) return answer; System.out.println("Entered value not in range [" + + low + ".." + hight + "]"); } } These overloaded forInt methods (two different signatures) are two of my favorites; they are general purpose methods that we can use in many different programs. In fact, I have put these methods in the Prompt class; also, one calls the other so it further illustrates the power of composing methods (even the first calls two other methods: Integer.parseInt and Prompt.forString). The first forInt uses a try-catch to ensure that the value entered by the user (read as a String) is in fact a legal int (in which case it immediately returns that value); if the user doesn't enter a legal value, Integer.parseInt instead throws NumberFormatException; it is caught and processed by printing an error message and executing loop again, prompting the user to enter a value. The second forInt is passed three parameters, which are used to coordinate prompting the user with a message to enter a value between a lower and higher bound; the method rejects any entered values that are outside this range, prompting the user until he/she enters a value in this range. By calling the previously defined forInt method, this method doesn't have to worry about exceptions caused by incorrect data entry: the other method handles those kinds of errors. Notice the sophisticated use of the return statements to terminate these method and return an answer. There is no need for a break statement because by terminating the method, the loop is terminated too. public static int multiRoll (DiceEnsemble d, int times) { int sum = 0; for (int i=1; i<=times; i++) sum += d.roll().pipSum(); //cascaded method call return sum; } Finally, this method rolls a DiceEnsemble object the required number of times, returning the sum of all the pips seen during all the rolls. So, we can pass reference types as parameters to methods as easily as primitive types. Here we use the generic identifier i as an index that counts the appropriate number of throws (and is used nowhere else in the code); we could have also written this as the countdown loop for (/*parameter intialized*/; times>0; times--) {... noting that the parameter times is initialized when the method is called (by its matching argument), so the for loop doesn't need to initialize it. In summary, we can define a simply-named method (with the parameters needed to do the calculation) and a body that hides the "messy" calculation. Then we can place it in a class, debug it, and forget about it. We are always only one method name away from hiding whatever complexity a program requires. By layering methods, we can quickly amplify their powers. Hand Simulation via Call Frames In this section we will begin to learn how to hand simulate method calls using the call frame mechanism, which is mostly concerned with passing the arguments at the method call site to the parameters in the method definition. We will expand upon this mechanism, to show its real predictive power, when we discuss passing references to objects into methods in the next section. The general form of a call frame is always the same. For a concrete example, let's see how to write a call frame for the min method definition, being called as Math.min(x,y+1). First, the parameter mechanism in Java is called copy by value. With copy by value, Java copies the value of each argument (arguments are evaluated when a method is called, at its call site) into a parameter variable: pictured, as always, a box labeled by its parameter's name and type. So, parameters are just special kinds of variables: each is always initialized by the value of it matching argument from the call site. There are no local variables here, so we leave blank that part of the call frame. After the call frame has been specified, and the parameters have been initialized, Java executes the body of the method, which refers to the parameters to compute its value. The result is that this method returns 5, which replaces the method call at the call site, in the System.out.println statement, so ultimately 5 is printed on the console. For another example, here is a call frame for the factorial method Note that after it returns to the call site, the value that it returns as a result is stored into the variable y. Besides its single parameter, this method declares two local variables (answer and i, the for loop index variable), which are initialized in their declarations to 1 and 2 respectively when Java executes the body of its method. Note how state changes to variable are illustrated: crossing out the old value and writing the new value after it. Advanced Call Frames In this section, we will explore call frames in a bit more detail, looking closely at the difference between changing the state of a variable and changing the state of an object (referred to by a variable). Let's start by hand simulating a call to the following method public static void swap (int a, int b) { int temp = a; a = b; b = temp; } Let's assume that this method is defined in a class named Utility and that we declare int x=5, y=8; and call Utility.swap(x,y); what values are ultimately stored in x and y? Are these variables swapped, or do they remain unchanged? The call frame shows us. IMPORTANT: If we do not execute a return; statement in a void method (there is none in the code below), Java automatically does the equivalent of return; when it reaches the end of the block that is the body of the method. Java DOES NOT allow an implicit return in a non-void method, becuase we MUST specify an expression that tells Java what value the method returns as its result; but, because void methods return nothing, Java can reasonably include an implicit return; at the end of the body. It is important to note that although the values in the parameters (a and b) are exchanged by this code, the values stored in the arguments (x and y) ARE NOT EXCHANGED. The values stored in the arguments were copied to the parameters, but this transmission mechanism is ONE-WAY ONLY: FROM ARGUMENTS TO PARAMETERS. Thus, parameter transmission is asymmetrical. If an argument is a variable, the value stored in that variable always remains unchanged by a method call, even if we change the value stored in its matching parameter. The value in the box of the argument cannot be changed in a method call. The situation gets a bit more complicated and interesting with references, because everything is more complicated and interesting with references. Recall how to copy a reference into a variable: make the variable refer to the same object (this describes how references are passed from arguments to parameters as well). Although the value in the box of the argument cannot be changed in a method call (it will still refer to the same object), the state of the object that it refers to CAN BE CHANGED in the body of the method by calling mutators/commands. Let's look at the call frame for the multiRoll method to illustrate his behavior. Assume again that this method is defined in a class named Utility and that we declare DiceEnsemble dice = new DiceEnsemble(2,6); and call System.out.println(Utility.multiRoll(dice,3)); Java passes the argument to the parameter by copying its reference, resulting in both the argument dice and the parameter d sharing the same object. Then, each time the multiRoll method calls d.roll(); the state of the shared object changes (see the rollCount and pips instance variables). The different values returned by getPipSum (7=2+5, 4=3+1, 5=1+4)account for the state changes shown for the local variable sum. So, the first statement prints the returned value from sum (16), and the second prints the value of rollCount from the object (now 3) In summary, we cannot change arguments in a method call by changing the values stored in their matching parameters. But, if an argument and parameter share an object, then we can change the state of that object by calling a mutator/command method in the method. Once the method returns its result, the argument must refer to the same object, but THAT OBJECT'S STATE CAN BE CHANGED. final parameters Finally, here is an update to the EBNF rule for parameter. It adds the option of specifying the keyword final before type. parameter <= [final] type identifier If a parameter variable is declared final, we must treat it like any other final variable: we cannot change its state. So, throughout the method body it will always store the value to which it was initialized by its matching argument. It is frequently (but not always) the case that a method examines but does not store into its parameters. So, most of the time we can specify that a parameter is final. But, most Java style standards DO NOT require specifying parameters as final, even if they remain unchanged in the body of a method. I'm still deciding what I think is right in this case; meanwhile, you can choose either to include final in the code you write, to emphasize that the parameter does not change, or omit it; whatever you choose, be consistent. Designing Methods When designing a method, first think of a descriptive name for it; then think about the other prototype information: what its return type is (if it is not void) and what parameters it needs (what are descriptive names for them and what are their types). Parameter variables are used to convey special information to the method; information that controls what a method computes. Methods may also have declare local variables, which are needed temporarily during the execution of a method; but these values do not have to be initialized by arguments outside the method. Finally, and this is typically the easiest part, write the statements that implement the method. Most methods perform no input/output (unless that is the primary purpose of the method). Notice above that except for the promptInt methods, no others perform input or output. In some sense, methods get their "inputs" through their parameters; they supply their "output" either through a returned result or by changing the state of the objects that their parameters refer to. So, do not write methods that perform input/output unless that is their primary purpose. EBNF for Defining Classes including Package and Imports Everything in Java is defined in a class: simple programs (as we will soon see), as well as library classes. The EBNF for a class relies heavily on the definition of full-member-definition (note package and class are keywords). package-declaration <= package package-name; class-body <= {full-member-definition} class-definition <= [package-statement] {import-declaration} access-modifiers class identifier { class-body } The braces in the last rule stand for themselves (in the previous rules they stand for standard EBNF repetition). Most classes in Java are defined in their own .java file (although we can and will later use one file to define multiple classes). Let's examine the three major parts of a class definintion. First, the package-statement. Every class is defined in one package, specified in the package-statement; if this option is omitted, the class is said to be defined in the anonymous package (the name of the anonymous packages has no characters in it). Whatever package this class is in, all other classes in that package are automatically imported for use in it. Second, if this class must refer to any classes in other packages, they must be imported explicitly in an import-declarations. Finally, the class itself is defined: it specifies its own access modifiers (almost always jut public) and includes any number of full-member-definitions. Here is a trivial but complete class named Application. It is defined in the anonymous package, imports a neccessary class from the course library, and has a main method that performs some trivial I/O on the console. import edu.cmu.cs.pattis.cs151xx.Prompt; public class Application { public static void main(String[] args) { int input = Prompt.forInt("Enter positive n"); System.out.println("You entered: " + n); } } Typically, such a class is stored in a file with the same first name as the class: Application.java. After discussing main methods, will see how to define complete classes for simple Java programs and libraries that define other methods. The main Method Any Java class can define a special main method as one of its members; but, a method with this name is special only if it has exactly the following access modifiers and header (This method specifies an array of String as its parameter, although we will not use this parameter until we study how to use Java from a command line; we will see below how to tell the Eclipse IDE which special main method to execute.) public static void main(String[] args) We can direct Java to start our program (a collection of one or more classes) automatically in any special main method. In fact, any project can include multiple classes, and each class can have its own special main method (this is actually quite useful, and we will discuss this feature when we discuss testing classes in more detail). In such a situation, we must tell Java WHICH special main method to start with. In Eclipse, we specify the class whose main method is to be run by selecting the class either in the Package Explorer or in the Editor. Methods in Applications We have seen how to declare one special static method in a class and have Java execute that method. Now we will learn how to define and call other static methods in a class. All we must do is place these other method definitions inside the class, along with the main method. Then, we can call these method from main or from each other. Any static method in a class can call any other static method in that same class, just by using its name and supplying arguments that match its signature (or, if overloaded, one of its signatures). We can also be a bit more consistent (and verbose) and call a static method by prepending the class name to the method's name. The following Application class shows a simple example of such code. import edu.cmu.cs.pattis.cs151xx.Prompt; public class Application { public static int factorial (int n) { int answer = 1; for (int i=2; i<=n; i++) answer *= i; return answer; } public static void main(String[] args) { int input = Prompt.forInt("Enter positive n"); System.out.println(input + "! = " + factorial(input)); } } Here, main prompts the user for a value (using the static forInt method in the imported Prompt class) and then uses that value as an argument to call the factorial method defined in this class. We have always called static methods in the form ClassName.methodName; and, in fact, we could write System.out.println(n + "! = " + Application.factorial(input)); But, if one method defined in a class calls another method defined in that same class, then we can shorten the call to just the method's name. Most programmers use this shortened form for method names. Another way to think about this issue is to imagine that a class is like a family: all members of the Application class belong to a family with that last name. Each defined member's name is like a first name. Members of the same family (class) can refer to each other by their first names only, without ambiguity. This is why main can refer just to factorial; we do not need to write Application.factorial. But, when refering to some static member OUTSIDE your family (class) you must use both its last and first name (separated, of course, by a period). This is why we write Math.sqrt and Prompt.forInt in main methods in the Application class. A more complicated and interesting example of static methods appears in the Date Calculator #1 program. This program defines and used five static methods (and twelve static fields). Definition Order Java uses a multi-pass compiler, which means that the methods and fields in a program can be defined in any order: Java first reads all the method headers and fields in the file, then in reads all the bodies, checking that they all use the types of these methods and fields correctly. One standard way to write methods is in the "natural" order: if the body of method b calls method a, then method a is defined before method b. For example, we might have the following program form method a's header {...no method calls...} method a's header {...call to a...} method c's header {...no method calls...} method d's header {...calls to b and c...} main methods' header {...calls to d and a...} In fact, there may be many natural orders: e.g., in this example we could also meet the natural criteria by defining method c before method b or even before method a. The main method calls lots of other methods, so it typically appears last in the file. In the "reverse natural" order: if the body of method a calls method a, then method a is defined after method b. In this case, the main method calls lots of other methods, so it typically appears first in the file. main methods' header {...calls to d and a...} method d's header {...calls to b and c...} method c's header {...no method calls...} method b's header {...call to a...} method a's header {...no method calls...} In this way, the most powerful methods appear at the top; we can read the details of how they work aftward. Because Java uses a multi-pass compiler, these two orderings, or any others, are all legal. When we discuss mutually recursive methods, we will return to this topic again. Now, some words on divide and conquer, and program complexity. Up until now, we have been putting all of our code in the main method, some of which have been a hundred or more lines of code. This practice is stopping here! From now on, we will be distributing complexity by writing methods, and placing them in the application program, or in class libraries. We can write, test, and debug each method (and each class) by idependently. Each method, including main, should not comprise more than one or two dozen statements; when a method gets too complicated (it does "this" and "that") then write a "this" method and a "that" method, and have the original method call these two new methods to get its job done. Another rule for keeping the complexity of each method small it to prohibit more than one loop (the most complex Java statement to think about) per method -or allow multiple loops, but not nested loops. Notice how the complexity has been distibuted in the date calculator program, in which each method, even main contains only a small number of statements. Throwing Exceptions (an introduction) We have already discussed how to handle thrown exceptions with try-catch statements. Now is an appropriate time to begin discussing the other end of exception processing: how to throw them them after detecting a problem. The EBNF rule for throwing an exception (using the keyword throw) is trivial: throw-statement <= throw expression; where there is a syntax constraint that expression must refer to an object constructed from a class descended from the Throwable class. We will discuss class hierarchies later; for now we have seen the names of a variety of classes descended from Throwable: EOFException, NumberFormatException, and most important for our current needs, IllegalArgumentException, and IllegalStateException. Exceptions are represented by classes; so, throwing an exception requires us to construct a new instance of the class, typically initializing its state by a String that describes the problem; this String can be further examined and printed when the exception is caught. Given that our factorial method only works for non-negative integers, we might modify it as follows, to detect a bad argument and throw IllegalArgumentException with an appropriate message (rather than just returning 1). Notice how throws IllegalArgumentException now appears in factorial's signature. public static int factorial (int n) throws IllegalArgumentException { if (n < 0) throw new IllegalArgumentException ("factorial: n ("+n+") must be non-negative"); int answer = 1; for (int i=2; i<=n; i++) answer *= i; return answer; } A simple if statement, the first in the method, determines whether or not the argument is bad, and if so throws an exception. It is common to check all the necessary preconditions on arguments at the start of a method's body, grouping such code together and separating it from the code that actually performs the method's task (which executes only after all the preconditions on the parameters have been checked). In this example, if the argument matching parameter n is a negative value, Java constructs an instance of the IllegalArgumentException class (initialized with an appropriate error message), and throws that exception. When a statement throws an exception, Java abandons sequential execution and tries to locate a catch clause to handle the exception, first inside the method in which it was thrown; if the method itself doesn't have one, Java goes back to the call site for the method (which is the body of some other method) and repeats this process there. If by repeating this process, Java eventually gets back to the special main method, and if there is no matching catch clause to handle the exception, Java prints the exception name, the exception's message (the String argument to the exceptions constructor), and a trace of all the methods that were called, leading up to the problem. We will use throw statements as we continue to learn about writing constructors and methods in classes. We will come back to the topic of throw statements and try-catch statements, and exception classes at least once more (in the context of class hierarchies), to help us further understand this complex error detection and recovery mechanism. There we will learn how to write new exception classes and the difference between checked and unchecked exceptions. Methods in Library Classes Although some static methods might be useful in just one application, many are general enough to be used in other (similar) applications. In Java, we can easily collect these methods into a class of related methods (all the source code in the same file), which we can easily import and use in other programs. The Math class in the standard Java library serves exactly this purpose, as doe the Prompt class in the course library: each collects together a group of math-related or console i/o related methods. For example, we ccould easily group together all of the static methods and fields from the date calculator program into a DateUtility class as is shown below. Then, we could use such a class library in any program that must deal with dates. Examine the Date Calculator #2 program to see exactly how this mechanism works in a project. public class DateUtility { //Returns whether year is a leap year? public static boolean isLeapYear (int year) {return (year%4 == 0 && year%100 != 0) || year%400 == 0;} //Returns the number of days in month (in year) public static int daysIn (int month, int year) throws IllegalArgumentException { if (year < 1) throw new IllegalArgumentException ("daysIn: year ("+year+") not positive"); if (month < JANUARY || month > DECEMBER) throw new IllegalArgumentException ("daysIn: month ("+month+") not in range [1,12]"); //Thirty days hath September, April, June and November... if (month == APRIL || month == JUNE || month == SEPTEMBER || month == NOVEMBER) return 30; //...all the rest have thirty one... else if (month == JANUARY || month == MARCH || month == MAY || month == JULY || month == AUGUST || month == OCTOBER || month == DECEMBER) return 31; //...except February (must be FEBRUARY in else: see possible exception) else /* if (month == FEBRUARY) */ return 28 + (isLeapYear(year) ? 1 : 0); } //Returns the ordinal (1st, 2nd, 3rd, etc) representing month, day, year public static int ordinalDate (int month, int day, int year) { int ordinal = 0; //Scan every earlier month, summing the # of days in that month... for (int m=JANUARY; m < month; m++) ordinal += daysIn(m, year); //...and add day in the current month return ordinal + day; } //Returns a date as an American or European String //e.g., for February 10, 1954 these return "2/10/1954" and "10/2/1954" public static String americanFormat (int month, int day, int year) {return month + "/" + day + "/" + year;} public static String europeanFormat (int month, int day, int year) {return day + "/" + month + "/" + year;} //Fields: all public static final (constants supplied by class) //These could be private, for use only in this class, // but what the heck, let programmers use them from this class // (with final, there is nothing a programmer can do to change them) public static final int JANUARY = 1; public static final int FEBRUARY = 2; public static final int MARCH = 3; public static final int APRIL = 4; public static final int MAY = 5; public static final int JUNE = 6; public static final int JULY = 7; public static final int AUGUST = 8; public static final int SEPTEMBER = 9; public static final int OCTOBER = 10; public static final int NOVEMBER = 11; public static final int DECEMBER = 12; } Recall that final variables (constants) in Java are written as upper-case identifiers. If their name consists of multiple words, separate them by underscores: e.g., MAX_CLASS_SIZE. Given the use of a library class, the main method in the Application class must refer to its members by using both their class name and member name: e.g., int ordinal = DateUtility.ordinalDate(month, day, year); Again, observe that inside this class, we refer to each member by just its name. Outside the class (in the Application class) we must refer to each static member by its class name followed by its member name. Finally, note that there are no constructors for this class (and likewise no instance variables). We do not construct objects from this class; we just use the class name directly to refer to the methods that we want to call from this class. Methods/Fields and the Eclipse IDE Methods are so common in programming, various parts of the Eclipse IDE have been built to deal with them easily. Here we will examine mechanisms in the Java and Debugger views that help us use methods in our programs. The editor includes a mechanism to locate and display a method easily in a program or library class. When a class is active in the editor, the Outline window lists all the methods in the class. We can easily view a method in the editor by clicking its name in the Outline window. As the number of methods in a class grows, this mechanism becomes more and more useful for quickly navigating files. To the left of each method header is small shaded circle, containing either a minus sign or a plus sign. The minus sign means the method is fully disclosed; the plus sign means the method body is non-disclosed/elided (we see only its header). Clicking the circle toggles between disclosed and elided method bodies. We can also use the debugger to better understand methods and debug methods that we have written. The options displayed when we are stepping through a program appear as Middle: The Step Over button (the arrow pointing over a bar, as we have discussed) executes a method as if it were a black box: it does not show what happens inside a stepped-over method, it just executes its entire body in one fell swoop. Left: The Step Into button (the arrow pointing down between two bars) executes a method by first showing its parameters and local variables (in the Variables tab). Then, we can step through each statement in the method and watch how it executes. If we step through a return statement, we will be returned to the code that called the method. If the method we are stepping through calls another method, we can choose to step-into or step-over that other call. Right: The Step Out button (the arrow pointing up out of two bars) executes all the remaining statements in the current method, up to and including its return statement. Note, the single bar for the middle button represents an entire statement. Stepping over it means ignoring the details of any methods that are called in that statement. The double bars in the left and right buttons represent a block of code implementing a method. We can step into a method (start executing the first line of code in the methods) and step out of a method (finish executing the last line of code in the method). When we step into a method, its parameter and local variables appear in the Variables tab. All its parameters will be intialized to the values of their matching arguments. The name of the method will also appear underneath Thread[main] at in the Debug tab. If it calls another method, that method's name will appear above it (now directly underneath Thread[main]); whenever a method returns, its name is removed from the Debug tab and control returns to the method that called it (the one right below it in the Debug tab). If you click any method name in the Debug tab, it will show you the code that is executing in that method (in the editor window) and that method's parameters and local variables (in the Variables tab). In this way, it is easy to shift focus among the methods that are currently executing. The Application.main method remains at the bottom of these method names in the Debug tab, throughout the execution of the program. In the example below, we are looking at the bottom of the daysIn method; note its parameters have been initialized: month is 2 and year is 2006. In fact, this method has already called the isLeapYear method (it is at the top of the methods, so it is the one currently executing), but we have refocused our attention back to the daysIn method that called it, by selecting this method in the Debug tab. After we select the isLeapYear method and continue single-stepping, we return to the ordinalDate method, which shows the position it is executing (in the body of the loop) and all its parameters and local variables listed in the order they were declared in: parameters month, day, and year; local variables ordinal and m -the loop index. Practice using these three kinds of stepping using the two Date Calculator programs. The time you spend becoming familiar with debugging features will pay for itself many times over during the semester: debugging is hard, and these tools help tremendously. Defining Classes from which we Construct Objects We will now shift our focus from simple classes that have only static members towards more interesting and useful classes: those from which we can construct and manipulate objects/instances. We will first examine why/how these classes declare instance variables. Although instance variables are declared to be private, we wll learn that all other members in their class can manipulate them. Then we will learn how to write constructors that help initialize these instance variables. Finally, we will build on our knowledge of methods to learn how to write methods that manipulate instance variables. We will discuss multiple uses of the keyword this in the context of classes from which we construct objects Classes in Java combine elements of both state and behavior. State is embodied in an object's private instance variables; behavior is embodied in the class's public constructors and methods, which manipulate these instance variables. Programmers think about classes from three important and different viewpoints: user, implementor, and designer. When a programmer thinks about using a class, he/she is interested solely in its public members: what constructors can be used to to build objects and what methods can be called to perform useful operations on these objects. Such a programmer is interested in WHAT can be done, but not HOW it is done (so long as the implementation works and is efficient). Reading Javadoc is the prime way to learn this information. When a programmer thinks about implementing a class, he/she is interested first in what public members the class will supply (again, what programmers using the class will be able to do); but in addition, he/she is also interested in HOW such members can be implemented. Typically, knowing WHAT requires reading Javadoc; knowing HOW requires writing Java code that specifies what state each object will store and how its method bodies work to manipulate this state. This programmer is often presented with many interesting decisions, because there are many ways implement the same functionality. When a programmer thinks about designing a class, he/she is again interested solely in what public members the class supplies. This person must decide what members to include and then specify the semantics of each member so that (a) users understand WHAT to do with the class and (b) implementors understand HOW to implement it. Designers do this by writing the public prototypes in a class and documenting them with Javadoc. These three views are a bit of a simplification, because often one person takes multiple roles, even all three: a programmer might need to use a a class for a specific application, so he/she designs a general class that will be usable for that application (and hopefully others), and then he/she impelments the class; and closing the circle, he/she uses it in the application. Good design is hard. A designer often needs lots of experience using/implementing classes before he/she can effective design them (so others can use/implement them easily). In this course we will mostly take the roles of users (as we have in previous lectures) and implementors (as we will in this one). As implementors, we will typically be given a design, and then be required to implement it. To accomplish this process, we will have to indentify the state that each object stores, then declare it and define the required constructors and methods. Finally, who tests classes? We will see that classes may be tested from all three prespectives. The designer tests a class by developing a test suite along with the Javadoc; because the designer doesn't know anything about the implementation, this is black-box testing. Some test suites are open-ended (a driver) and some are closed (we will learn about JUnit testing). The implementor tests a class by running the designer's tests against the implementation, fixing errors exposed by the testing. The implementor might also develop further tests based on the actual implementation used (this is white-box testing). The user of a class implicitly tests it in an application program: if the application does not work as expected, it may indicate that the class(es) he/she is using are not correct (or, the user may just be using them incorrectly). The situation of a non-working application is interesting. Whose fault is it: the user of a class (for using it incorrectly) or the writer of a class (for implementing it incorrectly) We will examine this perspective at the end of the lecture, when we summarize classes (focusing on private members). The most important thing to know about a class is that any member defined in a class can refer to any other member defined in that same class, EVEN IF ITS ACCESS MODIFIER IS private. So, access modifiers restrict what members defined OUTSIDE a class can access; they do not restrict what members defined INSIDE a class can access. This rule allows a class implementor to declare instance variables private, so they cannot be directly accessed by code OUTSIDE the class, and still write constructors/method INSIDE the class that access them; in fact, often accessor/query methods just return the values stored in some private instance variable. To illustrate all this material, we will closely examine two classes and their drivers: SimpleDiceEnsemble and Rational. Instance Variables Let's start by looking at the implementation details for two sample classes. The SimpleDiceEnsemble class must store information characterizing the ensemble (number of dice and sides per die) and information about its current state (number of rolls, pip sum, whether all die show the same numer of pips). It declares its instance variables as follows. private int numberOfDice; private int sidesPerDie; private int rollCount; private int pipSum; private boolean allSame; The Rational class is much simpler: it must store only the numerator and denominator of the rational number (fraction). It declares its instance variables as follows. private int numerator; private int denominator; Classes typically group the declarations of all their fields at the top or bottom (although there are no rules requiring this placement) Recall that Javadoc pages show fields first, so declaring them at the top is reasonable. Another perspective is that instance variables are private details, so declaring them at the bottom (out of the way) is reasonable. Whenever new constructs an object, the first thing that it does is process all the field declarations in the class, which includes reserving space for all these field and initializing them. Unlike local variables, ALL FIELDS ARE INITIALIZED when they are declared: if we do not explicitly initialize them in their declarations, then Java implicitly initializes them: for the primitive types, it uses 0 for int, 0. for double, false for boolean, and the null character for char; for all reference types it uses null (meaning that they do not refer to any object). In the examples above, all instance variables are initialized to 0 and false; in SimpleDiceEnsemble it is as if we had explicitly written private int numberOfDice = 0; private int sidesPerDie = 0; private int rollCount = 0; private int pipSum = 0; private boolean allSame = false; We will soon see that constructors can (and often do) store more appropriate values in these variables, based on the arguments that we supply to the constructor. So technically, when a constructor stores a value into an instance variable, it is reinitialization, not initialization, because an initial value has already been stored there by Java, when it executes its declaration. Still, we will speak about initializing instance variables in constructors (and reinitialization if we want to be precise). Constructors The main purpose of any constructor is to ensure that all the instance variables of the object being constructed are initialized correctly. This is done in the body of the constructor, which contains exactly the same statements that can appear inthe body of a void method. For some instance variables a constructor may do nothing special: it leaves them with the initial values they received when declared. In other cases it initializes (actually reinitializes, given the discussion above) instance variables using the arguments passed to the constructor's parameters; the constructor often validates these arguments first (throwing IllegalArgumentException if they are incorrect). There are classes, some quite complicated, in which constructors take no arguments and reinitialize no fields. In these cases, the fields are initialized correctly in their declarations (either explicitly or implicitly). The Timer class is one example of this kind of class. Its constructor looks like public Timer () {} In fact, if we fail to define any constructor for a class, Java will automatically supply one that looks like this one (with the appropriate class name). But, if we define even one constructor for a class, Java will not overload the constructor(s) by defining this one. Most classes define at least one constructor (and many overload the constructor). These constructors always have parameter that help reinitialize instance variables. SimpleDiceEnsemble The first constructor defined in the SimpleDiceEnsemble class is public SimpleDiceEnsemble (int numberOfDice, int sidesPerDie) throws IllegalArgumentException { if (numberOfDice < 1) throw new IllegalArgumentException ("SimpleDiceEnsemble constructor: " + "Number of dice ("+numberOfDice+") < 1"); if (sidesPerDie < 1) throw new IllegalArgumentException ("SimpleDiceEnsemble constructor: " + "Sides per die ("+sidesPerDie+") < 1"); this.numberOfDice = numberOfDice; this.sidesPerDie = sidesPerDie; //rollCount: see declaration for implicit initializaton to 0 //pipCount and allSame indeterminate until roll } It first validates the values of its two parameters: if either does not make sense (we must have at least one die, and it must have at least one side), the constructor throws an IllegalArgumentException with an appropriate message. If the parameters do make sense, it copies them into two of the instance variables (reinitializing them). The other three instance variables are not reinitialized: the initial values they received when decared are correct: rollCount should always start at zero, and pipSum and allSame, although they store zero/false, really represent nothing, because the dice haven't been rolled yet (so any values would work for these). Interlude: Variable Name Conflicts and Resolving them with "this" We must take a briefly diversion to discuss variable name conflicts and how to resolve them with the keyword this. There are three kinds of variable names in Java. The name of a parameter (defined in the constructor/method header) The name of a local variable (defined in the constructor/method body) The name of a field (defined in its class) The Java compiler automatically implements a syntax constraint that prohibits defining a parameter with the same name as a local variable. So, the compiler would detect and report an error in following code public static int returnIt (int a) { int a = 1; return a; } In fact, Java points at the local variable declaration of a and says, "Variable 'a' is already defined in this method". But, Java does allow instance variables to have the same names as parameters or local variables. When this happens, it is called a variable name conflict, because when we use that common name, there is a conflict as to what it means. Whenever there is a variable name conflict, the name by itself NEVER refers to the instance variable; it ALWAYS refers to the parameter or local variable. If instead we want to refer to the instance variable, we must preface its name with this. (this is a keyword). In a constructor, this is a reference to the object being constructed; and this.numberOfDice refers to the numberOfDice instance variable defined inside the class. In fact, writing this.numberOfDice is always a legal way to refer to the numberOfDice instance variable in the object being constructed, whether or not there is a variable name conflict. So, in the constructor above, both parameter variables have a name conflict with two of the instance variables. The if statements, which check numberOfDice and sidesPerDie, are testing the parameter variables; the statements this.numberOfDice = numberOfDice; this.sidesPerDie = sidesPerDie; store the values of the parameter variables (which disappear when the constructor finishes executing) into the instance variables (which exist so long as the object they are in exists). If we wrote numberOfDice = numberOfDice; then Java would just store the parameter's value back into the parameter variable: it stores nothing into the instance variable! Such a statement can cause a very hard to locate bug! Another way around this whole "name conflict" problem is to change the parameter names; e.g. use number and sides. With no name conflicts, so we can write just numberOfDice = number; and sidesPerDie = sides. But, it is often the case that a well chosen name for an instance variable is replicated as a parameter name, because it captures exactly the right description; in such cases we must understand name conflicts and use this to resolve them. To help avoid confusion, some style guidelines for Java specify that every access to an instance variable should be prefixed by this. to indicated explicitly it that is accessing a field. I'm still on the fence about this style rule. Back to Discussing Constructors The second SimpleDiceEnsemble constructor has a much different form. First, it has no parameters; second, it does not throw any exceptions (this information is all specified in the constructor's header). We could have written this constructor as public SimpleDiceEnsemble () { numberOfDice = 2; sidesPerDie = 6; } which initializes the two instance variables so that the object represents two, six-sided dice. Note that because there are no parameter names in this constructor, so there are no name conflicts; therefore, we can use the instance variables directly with the this. prefix (although we could include this prefix for stylistic reasons). But Java provides an even simpler way to define this constructor (even if it requires us to learn a new language feature: a different context in which to use this). The actual constructor appears as public SimpleDiceEnsemble () {this(2,6);} In the constructor above this says "to initialize the instance variables, use another constructor from this class, one taking two int arguments. This is a common pattern, where one general constructor (with many parameters) is used by one or more special constructors (with fewer parameters) to do the initializations. Note that if we needed, we could add more statements to the constuctor AFTER this one (here, none are needed). In fact, another way to handle all the initialization in this class is to declare private int numberOfDice = 2; private int sidesPerDie = 6; private int rollCount; private int pipSum; private boolean allSame; The first constructor would work as before, reinitializing numberOfDice and sidesPerDie using the parameters. But the second constructor could be simplified to contain nothing in its body, because now when the instance variables are declared, they correctly represent two, six-sided dice. Thus, constructors act as middlemen: they accept arguments, check these values for correctness, and ultimately use them to (re)initialize instance variables (if they are correct). Because instance variables are private, they can be initialized only in the declaration themselves, and reinitialized by a constructor defined inside the class. Rational The first and most general constructor defined in the Rational class is public Rational (int numerator, int denominator) throws IllegalArgumentException { if (denominator == 0) throw new IllegalArgumentException ("Rational Construtor: - denominator 0"); if (numerator == 0) denominator = 1; //Ensure non-negative denominator; if a rational is // negative, its numerator is negative if (denominator < 0) { denominator = -denominator; numerator = -numerator; } //call gcd (greatest commmon divisor) // a private static method defined in this class int common = gcd(numerator,denominator); //or ...Rational.gcd(...) //name conflict this.numerator = numerator /common; this.denominator = denominator/common; } This constructor ultimately stores very special values into its two instance variables, carefully checking/altering its parameters before doing so. First, it cannot construct a rational value with a denominator or zero, is if the parameter has this values, it throws an exception. For all other numerators and denominators, it stores values according to the following rules. Zero is always stored as 0/1 The denominator is always stored as a positive value The numerator and denominator are reduced to have no common factors So, if we declare Rational x = new Rational(2,-4); then x refers to an object that stores -1 for the numerator and 2 for the denominator (try some other examples). The parameters are examined and changed as needed in all but the last two statements; at the end, this. is used to resolve the name conflicts. Note the call to the method gcd, which is a static method defined in this class. Any non-static method can call a static method. The following more special constructors create new objects by using this (in the sense of using another constructor in this class to initialize the instance variables) public Rational (int numerator) {this(numerator, 1);} public Rational () {this(0, 1);} In the first of these constructors, we specify a only a numerator parameter and by using this construct a rational with that value over 1; in the case of a parameterless constuctor, we construct a rational with the value 0 over 1; we could also have written this(0); Blank Final Recall that we can declare blank final local variables. We can also declare blank final instance variables, but we must follow and additional constraint. Java allows us to declare an intance variable final and not initialize it in its declaration (the definition of blank final) But, we must initialize this variable in EVERY constructor that we write, otherwise the Java compiler will detect and report an error. Of course, the Java compiler will ensure that we never try to assign a second value to any final variable, including final instance variables. Methods Method bodies follow the same rules as constructor bodies, in terms of their use of parameter variables, local variables, and instance variables (and in terms of this, variable name conflicts, etc). In fact, when we illustrate the call frame for a non-static method, it will show an implicit parameter named this and we will see how this parameter gets initialized by an implicit argument when such a method is called. Recall that methods are divided into two categories Mutator/command methods can access and store into instance variables declared in the class; they change the state of the object they are called on. Accessor/query methods can access instance variables declared in the class, but not store into them; they do not change the state of the object they are called on. We cannot tell just by looking at a method header whether it defines an accessor or a mutator (we must look at the method body or Javadoc). Yet, this is a fundamentally important piece of information about any method. Often, one can tell which it is by the name of the method: accessor method names often begin with get. Also, void methods are almost always mutators: if they don't return a result, the only interesting thing they can do is change the state of the object they were called on. Some methods, like nextToken in the StringTokenizer clas act as both a mutator/command and accessor/query: changing an object's state and returning some value. SimpleDiceEnsemble The SimpleDiceEnsemble class defines the roll method to be both a mutator/command and accessor/query (it is the only mutator in the class). It is defined as follows. public SimpleDiceEnsemble roll () { this.rollCount++; int firstThrow = this.randomDie(); this.pipSum = firstThrow; this.allSame = true; for (int i=2; i<=numberOfDice; i++) { int nextThrow = this.randomDie(); this.pipSum += nextThrow; this.allSame = this.allSame && (nextThrow == firstThrow); } return this; } Here, for clarity in the discussion to come, I have prefaced each instance variable by this. (even though there are no name conflicts). The roll method has no parameters; it declares two local variables (firstThrow and nextThrow) that it uses to change the rollCount, pipSum, and allSame instance variables Methods often have few or no parameters, because they primarily operate on the instance variables of an object. The pips showing for each die are computed by the randomDie method, which We will examine later. Let us see how to hand simulate a call to this method by using a call frame. Pay close attention to how this, the implicit parameter, is initialized by the implicit argument. Assume that we have declared SimpleDiceEnsemble dice = new SimpleDiceEnsemble(2,6); and now we execute the statement dice.roll(); We illustrate the call of this method by the call frame below (assume that we roll a 3 on the first die and a 5 on the second). The implicit parameter this appears in every non-static call frame; roll declares no explicit parameters. this is always initialized to refer to the object on which the method was called. In this case, the call was dice.roll() so dice is the implcit argument and this is initialized to refer to the same object as dice (the equivalent of this = dice, which looks a lot like an argument initializing a parameter, even though both are implicit). This method then examines and changes the instance variables in this object, as well as the local loop index variable i. Hand simulate this code, again assuming randomDie returns 3 when it is called the first time and 5 the second. Note that by writing this.rollCount we are explicitly showing which object is being referred to when the rollCount index variable is accessed. As stated above, even if we wrote just rollCount, because there are no name conflicts, the meaning of using this variable is exactly the same as this.rollCount. Notice too the call to this.randomDie(); it means to call the randomDie method on the object that this refers to, which is the same object on which roll is called. Generally, non-static methods inside a class can call other non-static methods in that same class, to help them accomplish their task on an object. As in the case of instance variables, writing randomDie() has exactly the same meaning here: calling another method on the same object that roll was called on. The randomDie method must be able to access the sidesPerDie instance variable to compute a random roll of a die with that many sides. In the actual code for SimpleDiceEnsemble, this is used only where necessary. Finally, the return statement returns the reference stored in this: the code above does nothing with the returned result, but if we had instead written System.out.Println(dice.roll().getPipSum()); Java would have called the getPipSum method on the returned reference, printing a value of 8. The SimpleDiceEnsemble class defines many accessor methods, two of which are shown below. public int getRollCount () {return rollCount;} public int getPipSum () throws IllegalStateException { if (rollCount == 0) throw new IllegalStateException("getPipSum - dice not rolled"); return pipSum; } Accessors are often simpler than mutators. The forms of many of these methods are actually quite common: just returning the value stored in one of the private instance variables. Note that by making the rollCount and pipSum instance variables private, no code external to the class can directly examine or change these variables, possibly trashing them; yet such code can always determine the current values stored in these instance variables indirectly, by calling their accessor/query methods. So, accessor/query methods allow any code to determine the value stored in a private instance variable without giving that code direct access to change that instance variable. Note that the second method first checks that the pipSum instance variable actually stores a computed value before returning it; if the dice have not yet been rolled, it throws the IllegalStateException: the object is not in a good state yet to call this method. Rational The Rational class is immutable. All its methods are accessors, although many construct and return values of primitive types or references to new Rational objects (the result of computing on the state(s) of old one(s), just as many String and BigInteger methods do). In the Rational class, I have adopted the style of always using this. when accessing instance variables. Two simple accessors that DO NOT construct objects are public int getNumerator() {return this.numerator;} public boolean equals (Rat

How to write an if-statement.

The if-then and if-then-else Statements The if-then Statement The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows: void applyBrakes() { // the "if" clause: bicycle must be moving if (isMoving){ // the "then" clause: decrease current speed currentSpeed--; } } If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement. In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement: void applyBrakes() { // same as above, but without braces if (isMoving) currentSpeed--; } Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results. The if-then-else Statement The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped. void applyBrakes() { if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } } The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on. class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println("Grade = " + grade); } } The output from the program is: Grade = C You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.

A bank charges $10 per month plus the following check fees for a commercial checking account: • $0.10 for each check if fewer than 20 checks were written during the month • $0.08 for each check if between 20 and 39 checks (inclusive) were written during the month • $0.06 for each check if between 40 and 59 checks (inclusive) were written during the month • $0.04 for each check if 60 or more checks were written during the month The bank also charges an extra $15 per month if the account balance is less than $400 (before any check fees are applied) at the end of the month. Design a class that stores the ending balance of an account and the number of checks written. It should also have a method that returns the bank's service fees for the month.

DaniWeb Read Contribute Search Search or jump to ... FORUM CATEGORIES laptop Hardware and Software code Programming live_tv Digital Media local_cafe Community Center ACTIVITIES Donate with PayPal forumLatest Posts Member Top List DaniWeb Ads Forum API Docs Community Rules About Us Contact Us © 2019 DaniWeb® LLC Homework Problem Home Programming Forum Software Development Forum Discussion Thread Member Avatar jwill222 8 Years Ago Ok so I've got this homework problem thats killing me. Here's the problem: A bank account charges $10 per month plus the following check fees for a commercial checking account: $.10 each for fewer than 20 checks $.08 each for 20-39 checks $.06 each for 40-59 checks $.04 each for 60 or more checks The bank also charges an extra $15 if the balance of the account falls below $400(before any check fees are applied). Write a program that asks for the beginning balance and the number of checks written. Compute and display the bank's service fees for the month. *Input validation*: Do not accept a negative value for the number of checks written. If a negative value is given for the beginning balance, display an urgent message indicating the account is overdrawn. This is the source code I got now(I've written like 5 of em)(please don't laugh) #include <iostream> using namespace std; int main() { int checks = 0; double balance,fee; cout << "Hello What's Your Balance? "<<endl; cin >> balance; if (balance <400 && >=0 ) { cout << "HOW MANY CHECKS HAVE YOU WRITTEN?"; cin >> checks; if (checks < 0) { cout "Can't do that"; } if (checks < 20 ) { fee = .10 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks <=39 && checks >=20){ fee = .08 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; }else if (checks <=59 && checks >=40 ){ fee = .06 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; }else if (checks >60 ){ fee = .04 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else { fee = .10 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } } else if ( balance >=400){ cout << "HOW MANY CHECKS HAVE YOU WRITTEN?"; cin >> checks; if (checks < 20) { fee = .10 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks <=39 && checks >=20){ fee = .08 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; }else if (checks <=59 && checks >=40 ){ fee = .06 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; }else if (checks >60 ){ fee = .04 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; } else if { fee = .10 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } } } Can a kind soul please help me with this. By, the way this source code has numerous errors in it but I just wanted to show everyone where I was going with it. The thing thats really throwing me off is the input validation part. If that wasn't there, I could do this no problem(lol I think) So can somebody please help me, I really wanna get this program done and get a full grasp of it c++ 4 Contributors forum7 Replies 503 Views 8 Years Discussion Span comment Latest Post 8 Years Ago by jwill222 Member Avatar VernonDozier 2,218 8 Years Ago Here's your code formatted and with the excess spacing removed. It's much easier to follow: #include <iostream> using namespace std; int main() { int checks = 0; double balance,fee; cout << "Hello What's Your Balance? "<<endl; cin >> balance; if (balance <400 && >=0 ) { cout << "HOW MANY CHECKS HAVE YOU WRITTEN?"; cin >> checks; if (checks < 0) { cout "Can't do that"; } if (checks < 20 ) { fee = .10 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks <=39 && checks >=20) { fee = .08 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks <=59 && checks >=40 ) { fee = .06 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks >60 ) { fee = .04 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else { fee = .10 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } } else if ( balance >=400) { cout << "HOW MANY CHECKS HAVE YOU WRITTEN?"; cin >> checks; if (checks < 20) { fee = .10 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks <=39 && checks >=20) { fee = .08 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks <=59 && checks >=40 ) { fee = .06 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; } else if (checks >60 ) { fee = .04 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; } else if { fee = .10 * checks + 10 ;] cout << " Bank Service charges for the month is "<< fee << " Dollars "; } } } Line 13 is illegal. if (balance <400 && >=0 ) Every comparison has to have something on both sides of the >= sign or <= sign or whatever. Correct syntax is this: if (balance <400 && balance >=0 ) Line 74 makes no sense. If you have an "else if", you need a condition. Perhaps you mean plain old "else"? Fix those two lines and hopefully it'll compile. There may be other errors, but those are the two that stick out to me. Member Avatar Nathaniel10 34 8 Years Ago Instead of all the else if statements, I would have used a switch statement. Member Avatar NathanOliver 429 8 Years Ago @ Nathaniel using a switch statement would be less than ideal in this case because you have a large range of numbers to work with. Even with fall through you would still need to have 60 cases. Member Avatar Nathaniel10 34 8 Years Ago @NathanOliver, I don't see that. There are 4 categories of fees on check so there are 4 cases. I was thinking along the lines of: double check_fees = 0.0; char level_checks = ' '; if (checks < 20) {level_checks = 'a';} if (checks => 20 && checks < 40) {level_checks = 'b';} if (checks => 40 && checks < 60) {level_checks = 'c';} switch (level_checks) { case 'a': check_fees = 0.10 * checks; break; case 'b': check_fees = 1.90 + 0.08 * (checks - 19); break; case 'c': check_fees = 1.90 + 1.52 + 0.06 * (checks - 39); break; default: check_fees = 1.90 + 1.52 + 1.14 + 0.04 * (checks - 59); break; } int low_balance = 0; if (balance < 400) {low_balance = 1;} fee = 10.0 + check_fees + 15.0 * low_balance; cout <<"Bank service charges for the month are $" << fee << " .\n"; Where do you see at least 60 cases? Member Avatar NathanOliver 429 8 Years Ago Doing the way you have done would not require 60 cases but why would you want to do it this way? It seems to me that it adds another layer of complexity. Since you are still using the if statements why not do the calculation in the body of the if statement? //... if (checks < 20) {check_fees = 0.10 * checks;} else if (checks => 20 && checks < 40) {check_fees = 1.90 + 0.08 * (checks - 19)} else if (checks => 40 && checks < 60) {check_fees = 1.90 + 1.52 + 0.06 * (checks - 39);} else {check_fees = 1.90 + 1.52 + 1.14 + 0.04 * (checks - 59)} //... Member Avatar Nathaniel10 34 8 Years Ago Your last post is better code than mine, Oliver. In any case, both were better than what the OP has. With yours, 8 lines of code does what the OP used 40 lines to do. Member Avatar jwill222 8 Years Ago Sorry guys I'm really not that experienced with C++ and programming in general, this is my first year in programming classes so I'm still learning.I appreciate everybody's input, I will surely continue to work hard and eventually get to u guys level lol. I just go with what I know, this is the final program though #include <iostream> #include <fstream> using namespace std; int main() { //Declare Variables and output file int checks = 0; double balance,fee;ofstream outData; outData.open("Pg.236number12.out"); //Get Balance from User cout << "Hello What's Your Balance? "<<endl; cin >> balance; //If Balance in the negative then display message that account is overdrawn if (balance <=-1) { cout << "Account is Overdrawn!!! OH NO!!!!"<<endl; outData<< "Accout is Overdrawn"<<endl;//Writes to output file } //if not continue to get the number of checks written else if (balance <400 && balance>=0 ) { //Get number of checks written cout << "HOW MANY CHECKS HAVE YOU WRITTEN?"<<endl; cin >> checks; //If negative value entered for checks display message if (checks <= -1) { cout << " No Negative Numbers Please!!! "<<endl; outData<< "No Negative Numbers Please!!! "<<endl; } /*If not continue on with fee calculations *note* extra 15 dollars charged for balances under $400*/ else if (checks < 20 ) { fee = .10 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData<< "Bank Service Charges for the month is "<< fee << "Dollars"; } else if (checks <=39 && checks >=20){ fee = .08 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData<< " Bank Service charges for the month is " << fee << " Dollars "<<endl; }else if (checks <=59 && checks >=40 ){ fee = .06 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData << " Bank Service charges for the month is "<< fee << "Dollars "<<endl; }else if (checks >60 ){ fee = .04 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; } else { fee = .10 * checks + 10 + 15; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; } } else if ( balance >=400){ cout << "HOW MANY CHECKS HAVE YOU WRITTEN?"<<endl; cin >> checks; if (checks <= -1) { cout << " No Negative Numbers Please!!! "; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; } else if (checks < 20 && checks>0) { fee = .10 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; } else if (checks <=39 && checks >=20){ fee = .08 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; }else if (checks <=59 && checks >=40 ){ fee = .06 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars "; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; }else if (checks >=60 ){ fee = .04 * checks + 10 ; cout << " Bank Service charges for the month is "<< fee << " Dollars " <<endl; outData<< " Bank Service charges for the month is "<< fee << "Dollars " <<endl; } else { fee = .10 * checks + 10 ; { cout << " Bank Service charges for the month is "<< fee << " Dollars "<<endl; outData<< " Bank Service charges for the month is "<< fee << "Dollars "<<endl; } } } } Related Topics Member Avatar Sales problem c++ Member Avatar recursion problem c++ Member Avatar Draw a tree homework problem Member Avatar Don't know how to start on a homework problem Member Avatar c++ homework problem Member Avatar C++ Basic Homework Problem Member Avatar Help with a homework problem? Member Avatar Hailstone c++ homework problem - what's wrong with my code? Member Avatar Hello, need help with this homework problem. Member Avatar Tough Problem [C and C++] Not what you need? add_comment Reply to this Topic

What a decision structure is.

Advertisements. Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

What packages are, how to make them available to your programs, and how to use their contents.

Packages and interfaces are two capabilities that allow you greater control and flexibility in designing sets of interrelated classes. Packages allow you to combine groups of classes and control which of those classes are available to the outside world; interfaces provide a way of grouping abstract method definitions and sharing them among classes that may not necessarily acquire those methods through inheritance. Today you'll learn how to design with, use, and create your own packages and interfaces. Specific topics you'll learn about today include A discussion of designing classes versus coding classes and how to approach each What packages are and why they are useful for class design Using other people's packages in your own classes Creating your own packages What interfaces buy you in terms of code reuse and design Designing and working with interfaces Programming in the Large and Programming in the Small When you examine a new language feature, you should ask yourself two questions: How can I use it to better organize the methods and classes of my Java program? How can I use it while writing the actual Java code? The first is often called programming in the large, and the second, programming in the small. Bill Joy, a founder of Sun Microsystems, likes to say that Java feels like C when programming in the small and like Smalltalk when programming in the large. What he means by that is that Java is familiar and powerful like any C-like language while you're coding individual lines, but has the extensibility and expressive power of a pure object-oriented language like Smalltalk while you're designing. The separation of "designing" from "coding" was one of the most fundamental advances in programming in the past few decades, and object-oriented languages such as Java implement a strong form of this separation. The first part of this separation has already been described on previous days: When you develop a Java program, first you design the classes and decide on the relationships between these classes, and then you implement the Java code needed for each of the methods in your design. If you are careful enough with both these processes, you can change your mind about aspects of the design without affecting anything but small, local pieces of your Java code, and you can change the implementation of any method without affecting the rest of the design. As you begin to explore more advanced Java programming, however, you'll find that this simple model becomes too limiting. Today you'll explore these limitations, for programming in the large and in the small, to motivate the need for packages and interfaces. Let's start with packages. What Are Packages? Packages, as mentioned a number of times in this book so far, are a way of organizing groups of classes. A package contains any number of classes that are related in purpose, in scope, or by inheritance. Why bother with packages? If your programs are small and use a limited number of classes, you may find that you don't need to explore packages at all. But the more Java programming you do, the more classes you'll find you have. And although those classes may be individually well designed, reusable, encapsulated, and with specific interfaces to other classes, you may find the need for a bigger organizational entity that allows you to group your packages. Packages are useful for several broad reasons: They allow you to organize your classes into units. Just as you have folders or directories on your hard disk to organize your files and applications, packages allow you to organize your classes into groups so that you only use what you need for each program. They reduce problems with conflicts in names. As the number of Java classes grows, so does the likelihood that you'll use the same class name as someone else, opening up the possibility of naming clashes and errors if you try to integrate groups of classes into a single program. Packages allow you to "hide" classes so that conflicts can be avoided. They allow you to protect classes, variables, and methods in larger ways than on a class-by-class basis, as you learned yesterday. You'll learn more about protections with packages later today. They can be used to identify your classes. For example, if you implemented a set of classes to perform some purpose, you could name a package of those classes with a unique identifier that identifies you or your organization. Although a package is most typically a collection of classes, packages can also contain other packages, forming yet another level of organization somewhat analogous to the inheritance hierarchy. Each "level" usually represents a smaller, more specific grouping of classes. The Java class library itself is organized along these lines. The top level is called java; the next level includes names such as io, net, util, and awt. The last of these has an even lower level, which includes the package image. Note By convention, the first level of the hierarchy specifies the (globally unique) name to identify the author or owner of those packages. For example, Sun Microsystems's classes, which are not part of the standard Java environment, all begin with the prefix sun. Classes that Netscape includes with its implementation are contained in the netscape package. The standard package, java, is an exception to this rule because it is so fundamental and because it might someday be implemented by multiple companies. I'll tell you more about package-naming conventions later when you create your own packages. Using Packages You've been using packages all along in this book. Every time you use the import command, and every time you refer to a class by its full package name (java.awt.Color, for example), you've used packages. Let's go over the specifics of how to use classes from other packages in your own programs to make sure you've got it and to go into greater depth than we have in previous lessons. To use a class contained in a package, you can use one of three mechanisms: If the class you want to use is in the package java.lang (for example, System or Date), you can simply use the class name to refer to that class. The java.lang classes are automatically available to you in all your programs. If the class you want to use is in some other package, you can refer to that class by its full name, including any package names (for example, java.awt.Font). For classes that you use frequently from other packages, you can import individual classes or a whole package of classes. After a class or a package has been imported, you can refer to that class by its class name. What about your own classes in your own programs that don't belong to any package? The rule is that if you don't specifically define your classes to belong to a package, they're put into an unnamed default package. You can refer to those classes simply by class name from anywhere in your code. Full Package and Class Names To refer to a class in some other package, you can use its full name: the class name preceded by any package names. You do not have to import the class or the package to use it this way: java.awt.Font f = new java.awt.Font() For classes that you use only once or twice in your program, using the full name makes the most sense. If, however, you use that class multiple times, or if the package name is really long with lots of subpackages, you'll want to import that class instead to save yourself some typing. The import Command To import classes from a package, use the import command, as you've used throughout the examples in this book. You can either import an individual class, like this: import java.util.Vector; or you can import an entire package of classes, using an asterisk (*) to replace the individual class names: import java.awt.* Note Actually, to be technically correct, this command doesn't import all the classes in a package-it only imports the classes that have been declared public, and even then only imports those classes that the code itself refers to. You'll learn more on this in the section titled "Packages and Class Protection." Note that the asterisk (*) in this example is not like the one you might use at a command prompt to specify the contents of a directory or to indicate multiple files. For example, if you ask to list the contents of the directory classes/java/awt/*, that list includes all the .class files and subdirectories, such as image and peer. Writing import java.awt.* imports all the public classes in that package, but does not import subpackages such as image and peer. To import all the classes in a complex package hierarchy, you must explicitly import each level of the hierarchy by hand. Also, you cannot indicate partial class names (for example, L* to import all the classes that begin with L). It's all the classes in a package or a single class. The import statements in your class definition go at the top of the file, before any class definitions (but after the package definition, as you'll see in the next section). So should you take the time to import classes individually or just import them as a group? It depends on how specific you want to be. Importing a group of classes does not slow down your program or make it any larger; only the classes you actually use in your code are loaded as they are needed. But importing a package does make it a little more confusing for readers of your code to figure out where your classes are coming from. Using individual imports or importing packages is mostly a question of your own coding style. Technical Note Java's import command is not at all similar to the #include command in C-like languages, although they accomplish similar functions. The C preprocessor takes the contents of all the included files (and, in turn, the files they include, and so on) and stuffs them in at the spot where the #include was. The result is an enormous hunk of code that has far more lines than the original program did. Java's import behaves more like a linker; it tells the Java compiler and interpreter where (in which files) to find classes, variables, method names, and method definitions. It doesn't bring anything into the current Java program. Name Conflicts After you have imported a class or a package of classes, you can usually refer to a class name simply by its name, without the package identifier. I say "usually" because there's one case where you may have to be more explicit: when there are multiple classes with the same name from different packages. Here's an example. Let's say you import the classes from two packages from two different programmers (Joe and Eleanor): import joesclasses.*; import eleanorsclasses.*; Inside Joe's package is a class called Name. Unfortunately, inside Eleanor's package there is also a class called Name that has an entirely different meaning and implementation. You would wonder whose version of Name would end up getting used if you referred to the Name class in your own program like this: Name myName = new Name("Susan"); The answer is neither; the Java compiler will complain about a naming conflict and refuse to compile your program. In this case, despite the fact that you imported both classes, you still have to refer to the appropriate Name class by full package name: joesclasses.Name myName = new joesclasses.Name("Susan"); A Note About CLASSPATH and Where Classes Are Located Before I go on to explain how to create your own packages of classes, I'd like to make a note about how Java finds packages and classes when it's compiling and running your classes. For Java to be able to use a class, it has to be able to find it on the file system. Otherwise, you'll get an error that the class does not exist. Java uses two things to find classes: the package name itself and the directories listed in your CLASSPATH variable. First, the package names. Package names map to directory names on the file system, so the class java.applet.Applet will actually be found in the applet directory, which in turn will be inside the java directory (java/applet/Applet.class, in other words). Java looks for those directories, in turn, inside the directories listed in your CLASSPATH variable. If you remember back to Day 1, "An Introduction to Java Programming," when you installed the JDK, you had to set up a CLASSPATH variable to point to the various places where your Java classes live. CLASSPATH usually points to the java/lib directory in your JDK release, a class directory in your development environment if you have one, perhaps some browser-specific classes, and to the current directory. When Java looks for a class you've referenced in your source, it looks for the package and class name in each of those directories and returns an error if it can't find the class file. Most "cannot load class" errors result because of missed CLASSPATH variables. Note If you're using the Macintosh version of the JDK, you're probably wondering what I'm talking about. The Mac JDK doesn't use a CLASSPATH variable; it knows enough to be able to find the default classes and those contained in the current directory. However, if you do a lot of Java development, you may end up with classes and packages in other directories. The Java compiler contains a Preferences dialog box that lets you add directories to Java's search path. Creating Your Own Packages Creating your own packages is a difficult, complex process, involving many lines of code, long hours late at night with lots of coffee, and the ritual sacrifice of many goats. Just kidding. To create a package of classes, you have three basic steps to follow, which I'll explain in the following sections. Pick a Package Name The first step is to decide what the name of your package is going to be. The name you choose for your package depends on how you are going to be using those classes. Perhaps your package will be named after you, or perhaps after the part of the Java system you're working on (like graphics or hardware_interfaces). If you're intending your package to be distributed to the Net at large, or as part of a commercial product, you'll want to use a package name (or set of package names) that uniquely identifies you or your organization or both. One convention for naming packages that has been recommended by Sun is to use your Internet domain name with the elements reversed. So, for example, if Sun were following its own recommendation, its packages would be referred to using the name com.sun.java rather than just java. If your Internet domain name is fooblitzky.eng.nonsense.edu, your package name might be edu.nonsense.eng.fooblitzky (and you might add another package name onto the end of that to refer to the product or to you, specifically). The idea is to make sure your package name is unique. Although packages can hide conflicting class names, the protection stops there. There's no way to make sure your package won't conflict with someone else's package if you both use the same package name. By convention, package names tend to begin with a lowercase letter to distinguish them from class names. Thus, for example, in the full name of the built-in String class, java.lang.String, it's easier to separate the package name from the class name visually. This convention helps reduce name conflicts. Create the Directory Structure Step two in creating packages is to create a directory structure on your disk that matches the package name. If your package has just one name (mypackage), you'll only have to create a directory for that one name. If the package name has several parts, however, you'll have to create directories within directories. For the package name edu.nonsense.eng.fooblitzky, you'll need to create an edu directory and then create a nonsense directory inside edu, an eng directory inside nonsense, and a fooblitzky directory inside eng. Your classes and source files can then go inside the fooblitzky directory. Use package to Add Your Class to a Package The final step to putting your class inside packages is to add the package command to your source files. The package command says "this class goes inside this package," and is used like this: package myclasses; package edu.nonsense.eng.fooblitzky; package java.awt; The single package command, if any, must be the first line of code in your source file, after any comments or blank lines and before any import commands. As mentioned before, if your class doesn't have a package command in it, that class is contained in the default package and can be used by any other class. But once you start using packages, you should make sure all your classes belong to some package to reduce the chance of confusion about where your classes belong. Packages and Class Protection Yesterday you learned all about the four Ps of protection and how they apply (primarily) to methods and variables and their relationship to other classes. When referring to classes and their relationship to other classes in other packages, you only have two Ps to worry about: package and public. By default, classes have package protection, which means that the class is available to all the other classes in the same package but is not visible or available outside that package-not even to subpackages. It cannot be imported or referred to by name; classes with package protection are hidden inside the package in which they are contained. Package protection comes about when you define a class as you have throughout this book, like this: class TheHiddenClass extends AnotherHiddenClass { ... } To allow a class to be visible and importable outside your package, you'll want to give it public protection by adding the public modifier to its definition: public class TheVisibleClass { ... } Classes declared as public can be imported by other classes outside the package. Note that when you use an import statement with an asterisk, you import only the public classes inside that package. Hidden classes remain hidden and can be used only by the other classes in that package. Why would you want to hide a class inside a package? For the same reason you want to hide variables and methods inside a class: so you can have utility classes and behavior that are useful only to your implementation, or so you can limit the interface of your program to minimize the effect of larger changes. As you design your classes, you'll want to take the whole package into consideration and decide which classes will be declared public and which will be hidden. Listing 16.1 shows two classes that illustrate this point. The first is a public class that implements a linked list; the second is a private node of that list. Listing 16.1. The public class LinkedList. 1: package collections; 2: 3: public class LinkedList { 4: private Node root; 5: 6: public void add(Object o) { 7: root = new Node(o, root); 8: } 9: . . . 10: } 11: 12: class Node { // not public 13: private Object contents; 14: private Node next; 15: 16: Node(Object o, Node n) { 17: contents = o; 18: next = n; 19: } 20: . . . 21: } Note Notice here that I'm including two class definitions in one file. I mentioned this briefly on Day 13, "Creating User Interfaces with the awt," and it bears mentioning here as well: You can include as many class definitions per file as you want, but only one of them can be declared public, and that filename must have the same name as the one public class. When Java compiles the file, it'll create separate .class files for each class definition inside the file. In reality, I find the one-to-one correspondence of class definition to file much more easily maintained because I don't have to go searching around for the definition of a class. The public LinkedList class provides a set of useful public methods (such as add()) to any other classes that might want to use them. These other classes don't need to know about any support classes LinkedList needs to get its job done. Node, which is one of those support classes, is therefore declared without a public modifier and will not appear as part of the public interface to the collections package. Note Just because Node isn't public doesn't mean LinkedList won't have access to it once it's been imported into some other class. Think of protections not as hiding classes entirely, but more as checking the permissions of a given class to use other classes, variables, and methods. When you import and use LinkedList, the Node class will also be loaded into the system, but only instances of LinkedList will have permission to use it. One of the great powers of hidden classes is that even if you use them to introduce a great deal of complexity into the implementation of some public class, all the complexity is hidden when that class is imported or used. Thus, creating a good package consists of defining a small, clean set of public classes and methods for other classes to use, and then implementing them by using any number of hidden (package) support classes. You'll see another use for hidden classes later today. What Are Interfaces? Interfaces, like the abstract classes and methods you saw yesterday, provide templates of behavior that other classes are expected to implement. Interfaces, however, provide far more functionality to Java and to class and object design than do simple abstract classes and methods. The rest of this lesson explores interfaces: what they are, why they're crucial to getting the most out of the Java language for your own classes, and how to use and implement them. The Problem of Single Inheritance When you first begin to design object-oriented programs, the concept of the class hierarchy can seem almost miraculous. Within that single tree you can express a hierarchy of different types of objects, many simple to moderately complex relationships between objects and processes in the world, and any number of points along the axis from abstract/general to concrete/specific. The strict hierarchy of classes appears, at first glance, to be simple, elegant, and easy to use. After some deeper thought or more complex design experience, however, you may discover that the pure simplicity of the class hierarchy is restrictive, particularly when you have some behavior that needs to be used by classes in different branches of the same tree. Let's look at a few examples that will make the problems clearer. Way back on Day 2, "Object-Oriented Programming and Java," when you first learned about class hierarchies, we discussed the Vehicle hierarchy, as shown in Figure 16.1. Figure 16.1 : The Vechicle hierarchy. Now let's add to that hierarchy and create the classes BritishCar and BritishMotorcycle underneath Car and Motorcycle, respectively. The behavior that makes a car or motorcycle British (which might include methods for leakOil() or electricalSystemFailure()) is common to both these classes, but because they are in very different parts of the class hierarchy, you can't create a common superclass for both of them. And you can't put the British behavior further up in the hierarchy because that behavior isn't common to all motorcycles and cars. Other than physically copying the behavior between the two classes (which breaks the object-oriented programming [OOP] rules of code reuse and shared behavior), how can you create a hierarchy like this? Let's look at an even thornier example. Say you have a biological hierarchy with Animal at the top, and the classes Mammal and Bird underneath. Things that define a mammal include bearing live young and having fur. Behavior or features of birds include having a beak and laying eggs. So far, so good, right? So how do you go about creating a class for the platypus, which has fur, has a beak, and lays eggs? You'd need to combine behavior from two classes to form the Platypus class. And, because classes can have only one immediate superclass in Java, this sort of problem simply cannot be solved elegantly. Other OOP languages include the concept of multiple inheritance, which solves this problem. With multiple inheritance, a class can inherit from more than one superclass and get behavior and attributes from all its superclasses at once. Using multiple inheritance, you could simply factor the common behavior of BritishCar and BritishMotorcycle into a single class (BritishThing) and then create new classes that inherit from both their primary superclass and the British class. The problem with multiple inheritance is that it makes a programming language far more complex to learn, to use, and to implement. Questions of method invocation and how the class hierarchy is organized become far more complicated with multiple inheritance, and more open to confusion and ambiguity. And because one of the goals for Java was that it be simple, multiple inheritance was rejected in favor of the simpler single inheritance. So how do you solve the problem of needing common behavior that doesn't fit into the strict class hierarchy? Java, borrowing from Objective-C, has another hierarchy altogether separate from the main class hierarchy, a hierarchy of mixable behavior classes. Then, when you create a new class, that class has only one primary superclass, but it can pick and choose different common behaviors from the other hierarchy. This other hierarchy is the interface hierarchy. A Java interface is a collection of abstract behavior that can be mixed into any class to add to that class behavior that is not supplied by its superclasses. Specifically, a Java interface contains nothing but abstract method definitions and constants-no instance variables and no method implementations. Interfaces are implemented and used throughout the Java class library whenever a behavior is expected to be implemented by a number of disparate classes. The Java class hierarchy, for example, defines and uses the interfaces java.lang.Runnable, java.util.Enumeration, java.util.Observable, java.awt.image.ImageConsumer, and java.awt.image.ImageProducer. Some of these interfaces you've seen before; others you'll see later in this book. Still others may be useful to you in your own programs, so be sure to examine the API to see what's available to you. Abstract Design and Concrete Implementation Throughout this book you've gotten a taste of the difference between design and implementation in object-oriented programming, where the design of a thing is its abstract representation and its implementation is the concrete counterpart of the design. You saw this with methods, where a method's signature defines how it's used, but the method implementation can occur anywhere in the class hierarchy. You saw this with abstract classes, where the class's design provides a template for behavior, but that behavior isn't implemented until further down in the hierarchy. This distinction between the design and the implementation of a class or a method is a crucial part of object-oriented programming theory. Thinking in terms of design when you organize your classes allows you to get the big picture without being bogged down in implementation details. And having the overall design already defined when you actually start implementing allows you to concentrate on those details solely for the class you're working on. This programming version of "think globally, act locally" provides a powerful way of thinking about how your classes and your programs and your overall designs are organized and how they interrelate. An interface is made up of a set of method signatures with no implementations, making it the embodiment of pure design. By mixing an interface in with your class, you're encompassing that design into your implementation. That design can then be safely included anywhere in the class hierarchy because there are no class-specific details of how an interface behaves-nothing to override, nothing to keep track of, just the name and arguments for a method. What about abstract classes? Don't abstract classes provide this same behavior? Yes and no. Abstract classes and the abstract methods inside them do provide a separation of design and implementation, allowing you to factor common behavior into an abstract superclass. But abstract classes can, and often do, contain some concrete data (such as instance variables), and you can have an abstract superclass with both abstract and regular methods, thereby confusing the distinction. Even a pure abstract class with only abstract methods isn't as powerful as an interface. An abstract class is simply another class; it inherits from some other class and has its place in the hierarchy. Abstract classes cannot be shared across different parts of the class hierarchy the way interfaces can, nor can they be mixed into other classes that need their behavior. To attain the sort of flexibility of shared behavior across the class hierarchy, you need an interface. You can think of the difference between the design and the implementation of any Java class as the difference between the interface hierarchy and the design hierarchy. The singly inherited class hierarchy contains the implementations where the relationships between classes and behavior are rigidly defined. The multiply inherited mixable interface hierarchy, however, contains the design and can be freely used anywhere it's needed in the implementation. This is a powerful way of thinking about the organization of your program, and although it takes a little getting used to, it's also a highly recommended one. Interfaces and Classes Classes and interfaces, despite their different definitions, have an awful lot in common. Interfaces, like classes, are declared in source files, one interface to a file. Like classes, they also are compiled using the Java compiler into .class files. And, in most cases, anywhere you can use a class (as a data type for a variable, as the result of a cast, and so on), you can also use an interface. Almost everywhere that this book has a class name in any of its examples or discussions, you can substitute an interface name. Java programmers often say "class" when they actually mean "class or interface." Interfaces complement and extend the power of classes, and the two can be treated almost exactly the same. One of the few differences between them is that an interface cannot be instantiated: new can only create an instance of a class. Implementing and Using Interfaces Now that you've grasped what interfaces are and why they're powerful (the "programming in the large" part), let's move on to actual bits of code ("programming in the small"). There are two things you can do with interfaces: use them in your own classes and define your own. Let's start with the former. The implements Keyword To use an interface, you include the implements keyword as part of your class definition. You did this back on Day 11, "More Animation, Images, and Sound," when you learned about threads and included the Runnable interface in your applet definition: // java.applet.Applet is the superclass public class Neko extends java.applet.Applet implements Runnable { // but it also has Runnable behavior ... } Because interfaces provide nothing but abstract method definitions, you then have to implement those methods in your own classes, using the same method signatures from the interface. Note that once you include an interface, you have to implement all the methods in that interface-you can't pick and choose the methods you need. By implementing an interface you're telling users of your class that you support all of that interface. (Note that this is another difference between interfaces and abstract classes-subclasses of the latter can pick which methods to implement or override and can ignore others.) After your class implements an interface, subclasses of your class will inherit those new methods (and can override or overload them) just as if your superclass had actually defined them. If your class inherits from a superclass that implements a given interface, you don't have to include the implements keyword in your own class definition. Let's examine one simple example-creating the new class Orange. Suppose you already have a good implementation of the class Fruit and an interface, Fruitlike, that represents what Fruits are expected to be able to do. You want an orange to be a fruit, but you also want it to be a spherical object that can be tossed, rotated, and so on. Here's how to express it all (don't worry about the definitions of these interfaces for now; you'll learn more about them later today): interface Fruitlike { void decay(); void squish(); . . . } class Fruit implements Fruitlike { private Color myColor; private int daysTilIRot; . . . } interface Spherelike { void toss(); void rotate(); . . . } class Orange extends Fruit implements Spherelike { . . . // toss()ing may squish() me (unique to me) } Note that the class Orange doesn't have to say implements Fruitlike because, by extending Fruit, it already has! One of the nice things about this structure is that you can change your mind about what class Orange extends (if a really great Sphere class is suddenly implemented, for example), yet class Orange will still understand the same two interfaces: class Sphere implements Spherelike { // extends Object private float radius; . . . } class Orange extends Sphere implements Fruitlike { . . . // users of Orange never need know about the change! } Implementing Multiple Interfaces Unlike the singly inherited class hierarchy, you can include as many interfaces as you need in your own classes, and your class will implement the combined behavior of all the included interfaces. To include multiple interfaces in a class, just separate their names with commas: public class Neko extends java.applet.Applet implements Runnable, Eatable, Sortable, Observable { ... } Note that complications may arise from implementing multiple interfaces-what happens if two different interfaces both define the same method? There are three ways to solve this: If the methods in each of the interfaces have identical signatures, you implement one method in your class and that definition satisfies both interfaces. If the methods have different parameter lists, it is a simple case of method overloading; you implement both method signatures, and each definition satisfies its respective interface definition. If the methods have the same parameter lists but differ in return type, you cannot create a method that satisfies both (remember, method overloading is triggered by parameter lists, not by return type). In this case, trying to compile a class that implements both interfaces will produce a compiler error. Running across this problem suggests that your interfaces have some design flaws that might need re-examining. Other Uses of Interfaces Remember that almost everywhere that you can use a class, you can use an interface instead. So, for example, you can declare a variable to be of an interface type: Runnable aRunnableObject = new MyAnimationClass() When a variable is declared to be of an interface type, it simply means that any object the variable refers to is expected to have implemented that interface-that is, it is expected to understand all the methods that interface specifies. It assumes that a promise made between the designer of the interface and its eventual implementors has been kept. In this case, because aRunnableObject contains an object of the type Runnable, the assumption is that you can call aRunnableObject.run(). The important thing to realize here is that although aRunnableObject is expected to be able to have the run() method, you could write this code long before any classes that qualify are actually implemented (or even created!). In traditional object-oriented programming, you are forced to create a class with "stub" implementations (empty methods, or methods that print silly messages) to get the same effect. You can also cast objects to an interface, just as you can cast objects to other classes. So, for example, let's go back to that definition of the Orange class, which implemented both the Fruitlike interface (through its superclass, Fruit) and the Spherelike interface. Here we'll cast instances of Orange to both classes and interfaces: Orange anOrange = new Orange(); Fruit aFruit = (Fruit)anOrange; Fruitlike aFruitlike = (Fruitlike)anOrange; Spherelike aSpherelike = (Spherelike)anOrange; aFruit.decay(); // fruits decay aFruitlike.squish(); // and squish aFruitlike.toss(); // things that are fruitlike do not toss aSpherelike.toss(); // but things that are spherelike do anOrange.decay(); // oranges can do it all anOrange.squish(); anOrange.toss(); anOrange.rotate(); Declarations and casts are used in this example to restrict an orange's behavior to acting more like a mere fruit or sphere. Finally, note that although interfaces are usually used to mix in behavior to other classes (method signatures), interfaces can also be used to mix in generally useful constants. So, for example, if an interface defined a set of constants, and then multiple classes used those constants, the values of those constants could be globally changed without having to modify multiple classes. This is yet another example of where the use of interfaces to separate design from implementation can make your code more general and more easily maintainable. Creating and Extending Interfaces After using interfaces for a while, the next step is to define your own interfaces. Interfaces look a lot like classes; they are declared in much the same way and can be arranged into a hierarchy, but there are rules for declaring interfaces that must be followed. New Interfaces To create a new interface, you declare it like this: public interface Growable { ... } This is, effectively, the same as a class definition, with the word interface replacing the word class. Inside the interface definition you have methods and constants. The method definitions inside the interface are public and abstract methods; you can either declare them explicitly as such, or they will be turned into public and abstract methods if you do not include those modifiers. You cannot declare a method inside an interface to be either private or protected. So, for example, here's a Growable interface with one method explicitly declared public and abstract (growIt()) and one implicitly declared as such (growItBigger()). public interface Growable { public abstract void growIt(); //explicity public and abstract void growItBigger(); // effectively public and abstract } Note that, as with abstract methods in classes, methods inside interfaces do not have bodies. Remember, an interface is pure design; there is no implementation involved. In addition to methods, interfaces can also have variables, but those variables must be declared public, static, and final (making them constant). As with methods, you can explicitly define a variable to be public, static, and final, or it will be implicitly defined as such if you don't use those modifiers. Here's that same Growable definition with two new variables: public interface Growable { public static final int increment = 10; long maxnum = 1000000; // becomes public static and final public abstract void growIt(); //explicitly public and abstract void growItBigger(); // effectively public and abstract } Interfaces must have either public or package protection, just like classes. Note, however, that interfaces without the public modifier do not automatically convert their methods to public and abstract nor their constants to public. A non-public interface also has non-public methods and constants that can be used only by classes and other interfaces in the same package. Interfaces, like classes, can belong to a package by adding a package statement to the first line of the class file. Interfaces can also import other interfaces and classes from other packages, just as classes can. Methods Inside Interfaces One trick to note about methods inside interfaces: Those methods are supposed to be abstract and apply to any kind of class, but how can you define parameters to those methods? You don't know what class will be using them! The answer lies in the fact that you use an interface name anywhere a class name can be used, as you learned earlier. By defining your method parameters to be interface types, you can create generic parameters that apply to any class that might use this interface. So, for example, take the interface Fruitlike, which defines methods (with no arguments) for decay() and squish(). There might also be a method for germinateSeeds(), which has one argument: the fruit itself. Of what type is that argument going to be? It can't be simply Fruit, because there may be a class that's Fruitlike (that is, implements the Fruitlike interface) without actually being a fruit. The solution is to declare the argument as simply Fruitlike in the interface: public interface Fruitlike { public abstract germinate(Fruitlike self) { ... } } Then, in an actual implementation for this method in a class, you can take the generic Fruitlike argument and cast it to the appropriate object: public class Orange extends Fruit { public germinate(Fruitlike self) { Orange theOrange = (Orange)self; ... } } Extending Interfaces As with classes, interfaces can be organized into a hierarchy. When one interface inherits from another interface, that "subinterface" acquires all the method definitions and constants that its "superinterface" defined. To extend an interface, you use the extends keyword just as you do in a class definition: public interface Fruitlike extends Foodlike { ... } Note that, unlike classes, the interface hierarchy has no equivalent of the Object class; this hierarchy is not rooted at any one point. Interfaces can either exist entirely on their own or inherit from another interface. Note also that, unlike the class hierarchy, the inheritance hierarchy is multiply inherited. So, for example, a single interface can extend as many classes as it needs to (separated by commas in the extends part of the definition), and the new interface will contain a combination of all its parent's methods and constants. Here's an interface definition for an interface called BusyInterface that inherits from a whole lot of other interfaces: public interface BusyInterface extends Runnable, Growable, Fruitlike, Observable { ...} In multiply inherited interfaces, the rules for managing method name conflicts are the same as for classes that use multiple interfaces; methods that differ only in return type will result in a compiler error. An Example: Enumerating Linked Lists To finish up today's lesson, here's an example that uses packages, package protection, and defines a class that implements the Enumeration interface (part of the java.util package). Listing 16.2 shows the code. Listing 16.2. Packages, classes, and interfaces. 1: package collections; 2: 3: public class LinkedList { 4: private Node root; 5: 6: . . . 7: public Enumeration enumerate() { 8: return new LinkedListEnumerator(root); 9: } 10: } 11: 12: class Node { 13: private Object contents; 14: private Node next; 15: 16: . . . 17: public Object contents() { 18: return contents; 19: } 20: 21: public Node next() { 22: return next; 23: } 24: } 25: 26: class LinkedListEnumerator implements Enumeration { 27: private Node currentNode; 28: 29: LinkedListEnumerator(Node root) { 30: currentNode = root; 31: } 32: 33: public boolean hasMoreElements() { 34: return currentNode != null; 35: } 36: 37: public Object nextElement() { 38: Object anObject = currentNode.contents(); 39: 40: currentNode = currentNode.next(); 41: return anObject; 42: } 43: } Here is a typical use of the enumerator: collections.LinkedList aLinkedList = createLinkedList(); java.util.Enumeration e = aLinkedList.enumerate(); while (e.hasMoreElements()) { Object anObject = e.nextElement(); // do something useful with anObject } Notice that, although you are using the Enumeration e as though you know what it is, you actually do not. In fact, it is an instance of a hidden class (LinkedListEnumerator) that you cannot see or use directly. By using a combination of packages and interfaces, the LinkedList class has managed to provide a transparent public interface to some of its most important behavior (via the already defined interface java.util.Enumeration) while still encapsulating (hiding) its two implementation (support) classes. Handing out an object like this is sometimes called vending. Often the "vendor" gives out an object that a receiver can't create itself but that it knows how to use. By giving it back to the vendor, the receiver can prove it has a certain capability, authenticate itself, or do any number of useful tasks-all without knowing much about the vended object. This is a powerful metaphor that can be applied in a broad range of situations. Summary Today you have learned how packages can be used to collect and categorize classes into meaningful groups. Packages are arranged in a hierarchy, which not only better organizes your programs but allows you and the millions of Java programmers out on the Net to name and share their projects uniquely with one another. You have also learned how to use packages, both your own and the many preexisting ones in the Java class library. You then discovered how to declare and use interfaces, a powerful mechanism for extending the traditional single inheritance of Java's classes and for separating design inheritance from implementation inheritance in your programs. Interfaces are often used to call common (shared) methods when the exact class involved is not known. You'll see further uses of interfaces tomorrow and the day after. Finally, you learned that packages and interfaces can be combined to provide useful abstractions, such as LinkedList, that appear simple yet are actually hiding almost all their (complex) implementation from their users. This is a powerful technique. Q&A Q: Can you use import some.package.B* to import all the classes in that package that begin with B? A: No, the import asterisk (*) does not act like a command-line asterisk. Q: Then what exactly does importing with an * mean? A: Combining everything said previously, this precise definition emerges: It imports all the public classes you use in your Java code that are directly inside the package named, and not inside one of its subpackages. (You can only import exactly this set of classes, or exactly one explicitly named class, from a given package.) By the way, Java only "loads" the information for a class when you actually refer to that class in your code, so the * form of import is no less efficient than naming each class individually. Q: Why is full multiple inheritance so complex that Java abandoned it? A: It's not so much that it is too complex, but that it makes the language overly complicated-and as you'll learn on Day 21, "Under the Hood," this can cause larger systems to be less trustworthy and thus less secure. For example, if you were to inherit from two different parents, each having an instance variable with the same name, you would be forced to allow the conflict and explain how the exact same reference to that variable name in each of your superclasses, and in you (all three), are now different. Instead of being able to call "super" methods to get more abstract behavior accomplished, you would always need to worry about which of the (possibly many) identical methods you actually wished to call in which parent. Java's run-time method dispatching would have to be more complex as well. Finally, because so many people would be providing classes for reuse on the Net, the normally manageable conflicts that would arise in your own program would be confounded by millions of users mixing and matching these fully multiply inherited classes at will. In the future, if all these issues are resolved, more powerful inheritance may be added to Java, but its current capabilities are already sufficient for 99 percent of your programs. Q: abstract classes don't have to implement all the methods in an interface themselves, but don't all their subclasses have to? A: Actually, no. Because of inheritance, the precise rule is that an implementation must be provided by some class for each method, but it doesn't have to be your class. This is analogous to when you are the subclass of a class that implements an interface for you. Whatever the abstract class doesn't implement, the first non-abstract class below it must implement. Then, any further subclasses need do nothing further. Q: You didn't mention callbacks. Aren't they an important use of interfaces? A: Yes, but I didn't mention them because a good example would be too bulky. Callbacks are often used in user interfaces (such as window systems) to specify what set of methods is going to be sent whenever the user does a certain set of things (such as clicking the mouse somewhere, typing, and so forth). Because the user interface classes should not "know" anything about the classes using them, an interface's ability to specify a set of methods separate from the class tree is crucial in this case. Callbacks using interfaces are not as general as using, for example, the perform: method of Smalltalk, however, because a given object can only request that a user interface object "call it back" using a single method name. Suppose that object wanted two user interface objects of the same class to call it back, using different names to tell them apart? It cannot do this in Java, and it is forced to use special state and tests to tell them apart. (I warned you that it was complicated!) So although interfaces are quite valuable in this case, they are not the ideal callback facility.


Conjuntos de estudio relacionados

Chapter 12: the therapeutic environment

View Set

Introduction to Social Work Final Study Test

View Set

411 Infectious Diseases & Vaccines

View Set