Exam 1 CS-1440 Java Programming Intro
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 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 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 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.
- 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 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.
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 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").
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 ag
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.
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
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 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
- 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
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".
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 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 the
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.
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).
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 concentratio
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.
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 << "
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 s
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).
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
- 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.... }
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) // constructo
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 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 keywor
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.
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.
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 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.
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 nam
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
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 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 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
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
- 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.
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).
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
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 .
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;
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.
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 sca
- 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.
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
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 proble
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: Bugzi
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 fun
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. Rul
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."
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
- 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 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
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 cir
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.
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"); } ..
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;
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
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 usi
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 v
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.
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 subclas
- 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
