Intro to Java Test Flashcards

(154 cards)

1
Q

How are comments made in Java?

A

The “//” marks the beginning of a comment. The compiler ignores everything from the double-slash to the end of the line.

Although comments are not required, they are very /important to programmers.

Most programs are much more complicated than this example, and comments help explain what’s going on.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a class header?

A

The line “public class HelloWorld” is known as a “class header”, and it marks the beginning of a class definition.

One of the uses of a class is to serve as a container for an application.

For now, just remember that a Java program must have at least one class definition.

The class header is the first line of code in a Java class and it defines the name of the class.

All Java classes must start with a capital letter

Class header has to have the same name as folder - “public class (name of class)”
- Class has to start with an uppercase letter!
- No spaces in names
- Can’t begin with number or include special characters

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is public?

A

“public” is a Java key word, and it must be written all in lowercase letters.

It is known as an “access specifier”, and it controls where the class may be accessed from.

The “public” specifier means access to the class is unrestricted. In other words, the class is “open to the public”

public means code can be accessed by any code in a package

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is class?

A

“class”, which must also be written in lowercase letters, is a Java key word that indicates the beginning of a class definition.

  1. You may create more than one class in a file, but you may have only one public class per Java file.
  2. When a Java file has a public class, the name of the public class must be the same as the name of the file (without the .java extension). For instance, the program below has a public class named “HelloWorld”, so it is stored in a file named HelloWorld.java.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is “Hello World”?

A

“HelloWorld” is the class name. This name was made up by the programmer.

The class could have been called “Pizza”, or “Dog”, or anything else the programmer wanted.

Programmer-defined names may be written in lowercase letters, uppercase letters, or a mixture of both.

In a nutshell, this line of code tells the compiler that a publicly accessible class named “HelloWorld” is being defined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does it mean to be case sensitive?

A

Java is a case-sensitive language. That means it regards uppercase letters as being entirely different characters than their lowercase counterparts. The word Public is not the same as public, and Class is not the same as class. Some words in a Java program must be entirely in lowercase, while other words may use a combination of lower and uppercase characters.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is {?

A

The line with the “{“ in the program is called a “left brace”, or an “opening brace”, and is associated with the beginning of the class definition.

All of the programming statements that are part of the class are enclosed in a set of braces.

/If you glance at the last line of the program, you will see the closing brace. Everything between the two braces is the body of the class named “Simple”.

NOTE! You will get a syntax error if you forget to place a closing brace. Every opening brace must have a closing brace.

Everything between these braces is the body of the “main” method.

{} = curly braces, () = parentheses, [] = square brackets
{}: represents the container (class) defined by the opening and closing of the container and “public static void main” (main method) is the container inside the container - the point of entry of application - tells the compiler to compile anything inside main method
{}: after the header

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a method header and a method?

A

The line “public static void main(String[] args)” is known as a method header, and it marks the beginning of a method.

A method can be thought of as a group of one or more programming statements that collectively have a name.

When creating a method, you must tell the compiler several things about it. That is why this line contains contains so many words.

At this point, the only thing you should be concerned about is that the name of the method is “main”, and the rest of the words are required for the method to be properly defined.

Every Java application must have a method named ‘main’. The main method is the starting point of an application. Main method - “public static void main(String[] args)” - container inside a container (starting point for application) - where you write the code you want the computer to run (source code)

Program should always have a main method named main

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What does the line System.out.println do? What is a string literal?

A

The line “System.out.println(“HelloWorld!”);” displays a message on the screen.

The message, “HelloWorld!” is printed without the quotation marks. In programming terms, the group of characters inside the quotation marks is called a “string literal”.

NOTE! This is the only line in the program that causes anything to be printed on the screen.

The other lines, like “public class HelloWorld” and “public static void main(String[ ] args)”, are necessary for the framework of your program, but they do not cause any screen output.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is a program?

A

Remember, a program is a set of instructions for the computer. If something is to be displayed on the screen, you must use a programming statement for that purpose.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

When and why do we use semicolon?

A

Notice that at the end of the line “System.out.println(“HelloWorld!”);” is a semicolon. Just as a period marks the end of a sentence, a semicolon marks the end of a statement in Java.

NOTE! Places not to place a semicolon:
- Comments
- Class headers
- After braces

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are print and println?

A

The print and println methods are used to display text output. They are part of the Java API, which is a collection of pre-written classes and methods for performing specific operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is console output?

A

In this lesson we will learn how to write programs that produce output on the screen.

The simplest type of output that a program can display on the screen is “console output”.

Console output is merely plain text. Performing output in Java, as well as many other tasks, is accomplished by using the Java API.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the Java API?

A

The term API stands for “Application Programmer Interface”.

The API is a standard library of pre-written classes for performing specific operations.

These classes and their methods are available to all Java programs.

The “print” and “println” methods are part of the API and provide ways for output to be displayed on the standard output device.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is System?

A

System is a class that is part of the Java API.

The System class contains objects and methods that perform system-level operations, such as sending output to the console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is out?

A

The out object has methods, such as “print” and “println”, for performing output on the system console, or standard output device.

The “out” object is a member of the System class. It provides methods for sending output to the screen.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What type of relationship do System, out and print have?

A

hierarchical relationship, This hierarchy explains why the statement that executes println is so long. The sequence System.out.println specifies that println is a member of out, which is a member of System.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is print and println in term of System.out.println?

A

The “print” and “println” methods are members of the “out” object. They actually perform the work of writing characters on the screen.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is an argument?

A

The value that is to be displayed on the screen is placed inside the parentheses. This value is known as an “argument”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is important to know about the println method?

A

An important thing to know about the println method is that after it displays its message, it advances the cursor to the beginning of the next line. The next item printed on the screen will begin in this position

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the print method?

A

The print method, which is also part of the System.out object, serves a purpose similar to that of println to display output on the screen. The print method, however, does not advance the cursor to the next line after its message is displayed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Explain what happens here:

System.out.print(“Programming is “);
System.out.println(“great fun!”);

A

An important concept to understand about these two lines of code is that, although the output is broken up into two programming statements, this program will still display the message on one line. The data that you send to the print method is displayed in a continuous stream. Sometimes this can produce less-than-desirable results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Does the layout of the actual output match the arragnment of the strings in the source code?

A

The layout of the actual output looks nothing like the arrangement of the strings in the source code.

First, even though the output is broken up into four lines in the source code, it comes out on the screen as one line.

Second, notice that some of the words that are displayed are not separated by spaces. The strings are displayed exactly as they are sent to the print method. If spaces are to be displayed, they must appear in the strings.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What are two ways to add spaces or indent lines?

A

There are two ways to fix this program. The most obvious way is to use println methods instead of print methods.

Another way is to use escape sequences to separate the output into different lines.

An escape sequence starts with the backslash character (), and is followed by one or more control characters.

It allows you to control the way output is displayed by embedding commands within the string itself.

The escape sequence that causes the output cursor to go to the next line is \n.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is \n and \t characters?
The \n characters are called the newline escape sequence. When the print or println method encounters \n in a string, it does not print the \n characters on the screen, but interprets them as a special command to advance the output cursor to the next line. There are several other escape sequences as well. For instance, \t is the tab escape sequence. When print or println encounters it in a string, it causes the output cursor to advance to the next tab position.
26
Why is it important to select the proper data type?
Computer programs collect pieces of data from the real world and manipulate them in various ways. There are many different types of data. Each variable is assigned a data type, which is the type of data a variable can hold. Selecting the proper data type is important because a variable's data type determines the amount of memory the variable uses, and the way the variable formats and stores data. It is important to select a data type that is appropriate for the type of data that your program will work with.
27
What are the common Java data types?
byte, int, short, float, and double
28
What is the general format for variable declaration?
A variable declaration takes the following general format: dataType VariableName; "dataType" is the name of the data type and "variableName" is the name of the variable.
29
What is a byte?
-128 and a maximum value of 127 (inclusive) 8 bit integer data type Byte can only hold a range of values between -128 and 127 --- only holds a limited range meaning less data needed for the computer to store the application in memory byte is a keyword and a data type
30
What is a short?
-32,768 and a maximum value of 32,767 (inclusive) 16 bit integer data type
31
What is an int?
-2^31 and a maximum value of 2^31 used to store integer values without decimal points 32 bit integer
32
What is a long?
-2^63 and a maximum value of 2^63 a primitive data type that represents a 64-bit signed two's complement integer. It is used when a wider range than int is needed.
33
What is a float?
32 bit number... -3.4^38 to +3.4^38 save floating point numbers and is less precise than the double data type. 7 points of precision
34
What is a double?
64 bit number... -1.7^308 to +1.7^308 It is used to store decimal numbers with a higher degree of precision compared to the float data type. 14 points of precision, more accurate but uses more memory to store
35
What do different datatypes hold?
Different DataTypes use different memory sizes For example, an int variable uses 4 bytes (32 bits), and a double variable uses 8 bytes (64 bits).
36
What are data types called?
These data types are called "primitive data types" because you cannot use them to create objects. Recall that an object has attributes and methods. With the primitive data types, you can only create variables, and a variable can only be used to hold a single value. Such variables do not have attributes or methods.
37
What are all integer data types? What can an integer variable hold?
The data types, byte, int, short, and long, are all integer data types. An integer variable can hold whole numbers such as 7, 125, -14, and 6928.
38
How to combine many varaibles of any given data type?
In most programs you will need more than one variable of any given data type. If a program uses three integers like length, width, and area, they could be declared separately like in the example we have seen above. It is easier, however, to combine the three variable declarations as follows... int length, width, area; You can declare several variables of the same type, simply by separating their names with commas. * You can declare variables on the same line -- Only if they are the same variable type *
39
What is an integer literal?
When you write an integer literal in your program code, Java assumes it to be of the int data type. For example, in "Example 1", the literals -20, 105, 120, and 189000 are all treated as integer values.
40
How do you force an integer literal to be treated as a long?
You can force an integer literal to be treated as a "long", however, by suffixing it with the letter L. For example, the value 57L would be treated as a long. You can use either an uppercase or a lowercase L. The lowercase L looks too much like the number 1, so you should always use the uppercase L. NOTE! You cannot embed commas in numeric literals. For example, the following statement will cause an error: int number = 1,257,649; // ERROR! This statement must be written as: int number = 1257649; // or int number = 1_257_649; //
41
What are floating point data types? What data types rep floating point numbers?
Whole numbers are not adequate for many jobs. If you are writing a program that works with dollar amounts or precise measurements, you need a data type that allows fractional values. In programming terms, these are called floating-point numbers. Values such as 1.7 and -45.316 are floating-point numbers. In Java there are two data types that can represent floating-point numbers. They are "float" and "double". The "float" data type is considered a single precision data type. It can store a floating-point number with 7 digits of accuracy. The double data type is considered a double precision data type. It can store a floating-point number with 15 digits of accuracy. The double data type uses twice as much memory as the float data type, A float variable occupies 4 bytes (32 bits) of memory, whereas a double variable uses 8 bytes (64 bits).
42
What are floating point literals? How do you force a double literal to be treated as a float?
When you write a floating-point literal in your program code, Java assumes it to be of the double data type. for example! in Example 2, the literals 29.75, 1.76, and 31.51 are all treated as double values. Because of this, a problem can arise when assigning a floating-point literal to a float variable. Java is a "strongly typed language" which means that it only allows us to store values of compatible data types in variables. A double value is not compatible with a float variable because a double can be much larger or much smaller than the allowable range for a float. As a result, code such as the following will cause an error: // float number2; // number2 = 23.5; // Error! You can force a double literal to be treated as a float, however, by suffixing it with the letter F or f. The preceding code can be rewritten in the following manner to prevent an error: float numberA; numberA = 23.5F;
43
How do you represent floating-point literals in scientific notation?
Java uses E notation to represent values in scientific notation. In E notation, the number 4.728197 x 10^04 would be 4.728197E4.
44
What is the boolean data type?
The boolean data type allows you to create variables that may hold one of two possible values: true or false, Example 4 demonstrates the declaration and assignment of a boolean variable: boolean bool; bool = true; System.out.println(bool); bool = false; System.out.println(bool);
45
What are variables of the boolean data type useful for?
Variables of the boolean data type are useful for evaluating conditions that are either true or false. We will be using boolean data types later on, however, for now just remember the following things: boolean variables may hold only the value true or false. The contents of a boolean variable may not be copied to a variable of any type other than boolean.
46
What is the char data type?
The char data type is used to store characters. A variable of the char data type can hold one character at a time. Character literals are enclosed in single quotation marks. The program in Example 5 uses a "char" variable. The character literals 'A' and 'B' are assigned to the variable.
47
What is the difference between charcater literals and string literals?
It is important that you do not confuse character literals with string literals, which are enclosed in double quotation marks. String literals cannot be assigned to char variables.
48
How do you concatenate strings? What is String?
- String is an array of characters - Primitive data types have limitations which fixed data type but in strings size is vary so that is the main reason why the the strings are non primitive - String in Java is itself is a class and has its own methods to manipulate and operate over object of String class - Starts with capital letter - a class that points to a complex object because of the way it stores data (points to a memory address that would store actual data and primitive data types points directly to data) Use “String” in front of variable name In double quotes Ie. String myVariable = “Hello World”; -- “String” is the class and “myVariable” or the variable name is the complex object String name = "Mr. Petti"; // "Mr. Petti" is the string literal. System.out.println(greeting + name); This statement prints the contents of "greeting" and concatenates it with "name".
49
What should be on the left and right side of the operand?
The operand on the left side of the = operator must be a variable name. The operand on the right side of the = symbol must be an expression that has a value.
50
What is variable initialization?
You may also assign values to variables as part of the declaration statement. This is known as initialization. Java also allows you to declare several variables and initialize only some of them.
51
What are the three types of operators?
Java offers A multitude of operators for manipulating data. Generally, there are three types of operators: unary, binary, and ternary. These terms reflect the number of operands an operator requires.
52
What are unary operators?
Unary operators require only a single operand. For example, consider the following expression: // // -5 // Of course, we understand this represents the value negative five. We can also apply the operator to a variable, as follows: // // -number // This expression gives the negative of the value stored in the variable "number". The minus sign, when used this way, is called the "negation operator". Because it requires only one operand, it is a "unary operator".
53
What are binary and ternary operators?
Binary operators work with two operands. and Ternary operators, as you may have guessed, require three operands Binary operators work with two operands. The binary operands include +, -, *, /, %
54
What does the addition operator?
The addition operator returns the sum of its two operands.
55
What does the subtraction operator do?
The subtraction operator returns the value from its right operand subtracted from its left operand.
56
What does the multiplication operator do?
// The multiplication operator returns the product of its two operands.
57
What does the division operator do?
The division operator returns the quotient of its left operand divided by its right operand
58
What is the modulus operator?
The modulus operator returns the remainder of a division operation involving two integers. Situations arise where you need to get the remainder of a division. Computations that detect odd numbers or are required to determine how many items are left over after division use the modulus operator
59
What does it mean for an operator to have a higher precedence?
double outcome; outcome = 12 + 6 / 3; System.out.println("Outcome is " + outcome); What value will be stored in outcome? The 6 is used as an operand for both the addition and division operators. The "outcome" variable could be assigned either 6 or 14, depending on when the division takes place. The answer is 14 because the division operator has higher precedence than the addition operator.
60
How does mathematical expressions work in Java?
Mathematical expressions are evaluated from left to right. When two operators share an operand, the operator with the highest precedence is evaluated first. Multiplication and division have higher precedence than addition and subtraction The multiplication, division, and modulus operators have the same precedence. The addition and subtraction operators have the same precedence. If two operators sharing an operand have the same precedence, they work according to their associativity. Associativity is either left to right or right to left.
61
How does operator and associativity work?
| Operator | Associativity | | - (unary negation) | Right to Left | | * % / | Left to Right | | + - | Left to Right | | | | | Operators | Associativity|
62
What happens when two integers are divided?
When both operands of the division operator are integers, the operator will perform integer division. This means the result of the division will be an integer as well. If there is a remainder, it will be discarded.
63
What happens when 5/2 occurs?
This code divides 5 \ 2 and assigns the result to number. What value will be stored in number? You would probably assume that 2.5 would be stored in number because that is the result your calculator shows when you divide 5 by 2. However, that is not what happens when the previous Java code is executed. Because the numbers 5 and 2 are both integers, the fractional part of the result will be thrown away, or truncated. As a result, the value 2 will be assigned to the number variable. In the previous code, it doesn't matter that number is declared as a double because the fractional part of the result is discarded before the assignment takes place. In order for a division operation to return a floating-point value, one of the operands must be of a floating-point data type. In this code, 5.0 is treated as a floating-point number, so the division operation will return a floating-point number. The result of the division is 2.5.
64
How are parentheses used in Java?
Parts of a mathematical expression may be grouped with parentheses to force some operations to be performed before others. In the statement below, the sum of a, b, c, and d is divided by 4.0.
65
How do you do exponents in Java?
The Math.pow method accepts two arguments as follows... Math.pow(base, exponent)
66
How do you square root?
result = Math.sqrt(a * a + b * b); System.out.println("Math.sqrt(a * a + b * b) = " + result);
67
How do you generate pi?
Math.PI
68
What is the round method?
areaRounded = Math.round(area); System.out.println("The area rounded is " + areaRounded); The round method rounds a number to the smallest or highest value
69
What is the ceil method?
System.out.println(Math.ceil(area)); The ceil method rounds a number to the highest possible value... e.g 4.4 to 5
70
What is the floor method?
System.out.println(Math.floor(area)); The floor method rounds a number to the lowest possible value... e.g 4.7 to 4
71
What is the absolute method?
System.out.println(Math.abs(m)); The absolute method returns the absolute value of a number. e.g -4.7 to 4.7
72
How do you calculate percentages in Java?
Determining percentages is a common calculation in computer programming. Although the % symbol is used in general mathematics to indicate a percentage, most programming languages (including Java) do not use the % symbol for this purpose. In a program, you have to convert a percentage to a floating-point number, just as you would if you were using a calculator. For example, 50 percent would be written as 0.5 and 2 percent would be written as 0.02.
73
What is Intellij?
IntelliJ - (IDE) Integrated Development Environment- allows you to program in any language - makes coding easier because it points out errors and things we miss
74
What is public and class?
Java keywords
75
How does the computer begin application?
Computer runs source code inside class header and looks for main method for source code to begin application
76
How do you make multi-line comments?
Multi line comment - type “/*” and IntelliJ will input “*/” and anything in between those symbols are a comment
77
Summarize System.out.println("Hello World"
System.out.println("Hello World") - system is a class, out is an object, println is a method - all methods are followed by an () - inside () is the argument Toolbox named system - out in a compartment - println is a tool that allow programmer to make code do something specific
78
When do you put semicolons?
Only put semicolons after statements not class header or main method
79
Files that end in .class are?
Files that end in .class - this is your byte code instructions
80
Does underscore show up in the output when doing days = 189_000?
no
81
What happens when you initialize a varaible as a float?
Even when you initialize variable as a float -- Java automatically assigns variables as a double to give you the maximum precision Strictly tell Java you want a float by putting a “f” after the value
82
What is it called when a variable is declared with no value?
If you create a variable with no value -- the variable is unassigned
83
What is the order of operator precendence?
All programming languages has operator precedence (not just Java) -- multiplication and division, modulus, then addition and subtraction is the order of operations
84
What do you do if it is 2 % 7?
2 % 7 -- seven can’t go into 2 -- how many times does 7 go into 2? -- no times so two is leftover If the number on the left is smaller than the number on the right, modulus equals number on the right If the number on the left is bigger than the number on right, modulus can be performed regularly
85
What should you look at when determining output?
WHEN DETERMINING OUTPUT: look at data type of variable AND data type of operands involved!
86
What happens when you do integer with integer, integer with double and double with double?
Integer with integer = integer result, integer and double = double result, double and double = double result
87
Do you have to import math for Java?
*** You don’t have to import anything -- using the upper case letter in math indicates that a class is being used -- make sure math is always upper case
88
When do you use a variable?
When the number s used more than once
89
What happens when we create a variable with an integer data type and assign it with a float?
If we create a variable with an integer data type and assign it with a float -- Java can’t allow it because they aren’t compatible -- two different data types -- won’t turn float into an integer because it will cause the value to lose data
90
What happens here: int a; short b = 2; a = b;
When we put an int into the a short --- short can accommodate int BUT if we put a int into a short it won’t be able to accommodate range data
91
Rank the data types from highest to lowest
Rank: (Highest to lowest) double, float, long, int, short, byte
92
What is widening conversion?
If you go from a lower ranked data type to a higher one -- widening conversion -- Java allows you to do that In assignment statements where values of lower-ranked data types are stored in variables of higher-ranked data types. Java automatically converts the lower-ranked value to the higher-ranked type. This is called a "widening conversion". For example, the following code demonstrates a "widening conversion", which takes place when an int value is stored in a double variable: double k; int m = 10; k = m;
93
What is narrowing conversion?
If you go from a higher ranked data type to a lower one -- narrowing conversion -- Java can’t perform this conversion A "narrowing conversion" is the conversion of a value to a lower-ranked type. For example, converting a double to an int would be a narrowing conversion. Because narrowing conversions can potentially cause a loss of data, Java does not automatically perform them.
94
What should you use if you want to put an int into a short?
Trying to put a int into a short won’t work unless you use a casting operator to make the int variable type into a short
95
How do you retain back the decimal place in this code: int pies = 10, people = 4; double piesPerPerson = pies / people;
Integer division would result in losing a floating point number decimal place lost -- cast either pies or people as a double to retain decimal place double piesPerPerson = (double)pies / people; OR Pies and people are evaluated first -- integer division makes answer equal 2 -- assign it a double 2.0 -- you have to make either one or the other a double (double)(pies / people);
96
What happens when two numbers of a different data type perform a calculation?
If two numbers of a different data type and you perform a calculation on them, the highest ranked data type will be the output
97
What is the error here: short firstNumber = 10, secondNumber = 20, thirdNumber; thirdNumber = firstNumber + secondNumber;
Error --- first and second number, despite being short, are holding integer values -- two integers numbers = integer data type result -- putting integer into a short -- narrowing conversion -- Java can’t do that Cast short to entire equation -- makes the result a short -- if you only casted one of the variables as a short answer would be integer still -- highest ranked data type thirdNumber = (short)(firstNumber + secondNumber)
98
What is a named constant? What is final?
- Named constant -- a variable that can’t change - Standard convention -- all capital letters = constant - you can't reinitialize a named constant double amount, balance = 2; final double INTEREST_RATE = 0.069; the keyword final means that the variable’s value cannot be changed once it has been assigned. The "final" keyword can be used in a variable declaration to make the variable a named constant. Named constants are initialized with a value, and that value cannot change during the execution of the program.
99
What should you do before a variable is stored?
Before a value can be stored in a variable, the value's data type must be compatible with the variable's data type. Java performs some conversions between data types automatically, but does not automatically perform any conversion that can result in the loss of data. Java also follows a set of rules when evaluating arithmetic expressions containing mixed data types.
100
What does it mean when it says that Java is a strongly typed language?
Java First checks for compatibility between variable data type and value data type. Java is a "strongly typed language". This means that before a value is assigned to a variable, Java checks the data type of the variable and the value being assigned to it to determine whether they are compatible.
101
What does this mean? int x; double y = 2.5; // x = y;
The assignment statement is attempting to store a double value (2.5) in an int variable. When the Java compiler encounters this line of code, it will respond with an error message. (The JDK displays the message "possible loss of precision.")
102
What does this mean? int a; // int can store larger numbers than a short short b = 2; // can only store -32768 to 32768 a = b;
Not all assignment statements that mix data types are rejected by the compiler. This assignment statement, which stores a short in an int, will work with no problems.
103
So why does Java permit a short to be stored in an int, but does not permit a double to be stored in an int?
The obvious reason is that a double can store fractional numbers and can hold values much larger than an int can hold. If Java were to permit a double to be assigned to an int, a loss of data would be likely. Just like officers in the military, the primitive data types are ranked. One data type outranks another if it can hold a larger number. For example, a float outranks an int, and an int outranks a short. Below is a list of numeric data types in order of their rank. The higher a data type appears in the list, the higher is its rank. //double // float // long // int // short // byte
104
What does the cast operator do?
The cast operator lets you manually convert a value, even if it means that a narrowing conversion will take place. Cast operators are unary operators that appear as a data type name enclosed in a set of parentheses. The operator precedes the value being converted.
105
What does this mean? double number = 2.1; int x = (int)number; // Run to see results System.out.println("number before conversion is " + number); System.out.println("number after conversion in variable x is " + x);
The cast operator in this statement is the word int inside the parentheses, It returns the value in "number", converted to an int. This converted value is then stored in x. "number" begins as a floating-point variable, such as a double. The value that is returned is truncated which means the fractional part of the number is lost. The original value in the "number" variable is not changed, however.
106
What does this mean? short littleNum; int bigNum = 32; littleNum = (short)bigNum;
In this example, the cast operator returns the value in "bigNum", converted to a short. The converted value is assigned to the variable "littleNum".
107
What happens when a casting operator is applied to a varaible?
Note that when a cast operator is applied to a variable, it does not change the contents of the variable. It only returns the value stored in the variable, converted to the specified data type. Recall from our earlier discussion that when both operands of a division are integers, the operation will result in integer division. This means that the result of the division will be an integer, with any fractional part of the result thrown away.
108
What does this mean? piesPerPerson = (double)(pies / people);
This statement does not convert the value in pies or people to a double, but converts the result of the expression pies / people. If this statement were used, an integer division operation would still have been performed. Here's why: The result of the expression pies / people is 2 (because integer division takes place). The value 2 converted to a double is 2.0. To prevent the integer division from taking place, one of the operands must be converted to a double.
109
What happens when values of the byte or short data types are used in arithmetic expressions?
One of the nuances of the Java language is the way it internally handles arithmetic operations on int, byte, and short variables. When values of the byte or short data types are used in arithmetic expressions, they are temporarily converted to int values. The result of an arithmetic operation using only a mixture of byte, short, or int values will always be an int. For example, assume that b and c in the following expression are short variables: // // b + c // Although both b and c are short variables, the result of the expression b + c is an int. This means that when the result of such an expression is stored in a variable, the variable must be an int or higher data type.
110
What happens where a mathematical expression has one or more values of the double, float, or long data types?
In situations where a mathematical expression has one or more values of the double, float, or long data types, Java strives to convert all of the operands in the expression to the same data type.
111
What are the specific rules that govern evaluation of these types of expressions with one or more valyes of double float or long data
1. If one of an operator's operands is a double, the value of the other operand will be converted to a double. The result of the expression will be a double. For example, in the following statement assume that "b" is a double and "c" is an int: * * a = b + c; The value in "c" will be converted to a double prior to the addition. The result of the addition will be a double, so the variable a must also be a double 2. If one of an operator's operands is a float, the value of the other operand will be converted to a float. The result of the expression will be a float. For example, in the following statement assume that "x" is a short and "y" is a float: * * z = x * y; * The value in x will be converted to a float prior to the multiplication. The result of the multiplication will be a float. So the variable "z" must also be either a double or a float. 3. If one of an operator's operands is a long, the value of the other operand will be converted to a long. The result of the expression will be a long. For example, in the following statement assume that "a" is a long and "b" is a short: * * c = a - b; * The variable "b" will be converted to a long prior to the subtraction. The result of the subtraction will be a long, so the variable "c" must also be a long, float, or double.
112
What is wrong here? double amount = 0, balance = 0; amount = balance * 0.069;
In such a program, two potential problems arise. First, it is not clear to anyone other than the original programmer 0.069 is final constant variable. It appears to be an interest rate, but in some situations there are fees associated with loan payments. How can the purpose of this statement be determined without painstakingly checking the rest of the program? The second problem occurs if this number is used in other calculations throughout the program and must be changed periodically. Assuming the number is an interest rate, what if the rate changes from 6.9 percent to 8.2 percent? The programmer would have to search through the source code for every occurrence of the number. Both of these problems can be addressed by using named constants, a named constant is a variable whose value is read only and cannot be changed during the program's execution. You can create such a variable in Java by using the "final" keyword in the variable declaration.
113
Why are constants written in uppercase?
It is not required that the variable name appear in all uppercase letters, but many programmers prefer to write them this way so they are easily distinguishable from regular variable names. An initialization value must be given when declaring a variable with the "final" modifier, or an error will result when the program is compiled. A compiler error will also result if there are any statements in the program that attempt to change the value of a "final" variable. An advantage of using named constants is that they make programs more self-documenting.
114
How do you Extract one and two from 12?
Step one: 12 / 10 = 1 Step two: 12 % 10 = 2
115
How do you extract from 127?
Step one: 127 / 100 = 1 Step two: 127 % 100 / 10 = 2 Step three: 127 % 10 = 7
116
What is the String class?
The class that is provided by the Java API for handling strings is named "String". The first step in using the String class is to declare a variable of the String class data type. Remember that a String is a class, not a primitive data type.
117
What are primitive type variables?
A variable of any type can be associated with an item of data. Primitive type variables hold the actual data items with which they are associated. For example, the following statement stores the value 25 in the "number" variable: int number = 25; The "number" variable holds the actual data with which it is associated
118
What are class type variables?
A class type variable does not hold the actual data item that it is associated with, but holds the memory address of the data item it is associated with. If "nameOne" is a String class variable, then "nameOne" holds the memory address of a String object. When a class type variable holds the address of an object, it is said that the variable references the object. For this reason, class type variables are commonly known as "reference variables".
119
What happens when creating a string object?
Any time you write a string literal in your program, Java will create a String object in memory to hold it. You can create a String object in memory and store its address in a String variable with a simple assignment statement. Here's an example: String s1 = "This is a String"; This statements declares a String variable named "s1" and assigns the String "This is a String"
120
Why is it useful for the string type to be a class?
Because the string type is a class instead of a primitive data type, it provides numerous methods for working with strings.
121
To call a method means?
To call a method means to execute it.
122
What is the general form of a method clall?
The general form of a method call is as follows: referenceVariable.method(arguments. . .) "referenceVariable" is the name of a variable that references an object, method is the name of a method, and arguments. . . is zero or more arguments that are passed to the method. If no arguments are passed to the method, as is the case with the length method, a set of empty parentheses must follow the name of the method.
123
What does this mean? String name = “Rob”
reference to a memory address and memory address make reference actual value your holding -- name is a reference variable String is a class and is a complex object
124
What is constructor method syntax?
another way to make a string
125
How is concatenating done with strings?
Concatenating -- not done in print line -- string reference variable = concatenation - concatenate integers and strings is okay
126
What does the length() do?
Look at nameFour -- get me the length of this string -- how many characters in the string where spaces in string count int variable data type -- variable will hold whole numbers to count Format: int + stringSize + = + name of variable holding string.length(); This method returns the number of characters in the string. The return value is of the type int.
127
What is toUpperCase()?
Loot at string in variable -- make characters uppercase -- assign it to outputA BUT the characters in nameFive don’t change (still lowercase) This method returns a new string that is the uppercase equivalent of the string contained in the calling object.
128
what is toLowerCase()?
Puts string back to lowercase -- if in println statement, it’s not assigned to a variable This method returns a new string that is the lowercase equivalent of the string contained in the calling object.
129
How do you return a specific charcater in a string?
How to return a specific character in a string -- **All indexes start at zero ** First number is always zero -- this is printing out the letter directly but you could do this by assigning it to a char variable char outputB = nameFive.charAt(4); charAt(index) The argument index is an int value and specifies a character position in the string. The first character is at position 0, the second character is at position 1, and so forth. The method returns the character at the specified position. The return value is of the type char.
130
How do you find the index of a specific letter in a string?
\”t\” -- puts quotes around t in output use indexOf() function returns the index of the first occurrence of a character specified by the user
131
What is contains()?
Contains method checks if characters in brackets are found in a variable holding a string -- it is a boolean method that evaluates true or false (found or not found in variable) returns "true" if the "contains" method finds a series of characters specified by the user.
132
What is a reference variable?
When a class type variable holds the address of an object, it is said that the variable references the object.
133
What is the standrad input device?
- Previously we discussed the System.out object, and how it refers to the standard output device. - The Java API has another object, System.in, which refers to the standard input device. The standard input device is normally the keyboard. You can use the System.in object to read keystrokes that have been typed at the keyboard. - However, using System.in is not as simple and straightforward as using System.out because the System.in object reads input only as byte values. This isn't very useful because programs normally require values of other data types as input. - To work around this, you can use the System.in object in conjunction with an object of the Scanner class. - The Scanner class is designed to read input from a source (such as System.in), and it, provides methods that you can use to retrieve the input formatted as primitive values or strings. First, you create a Scanner object and connect it to the System.in object.
134
What does this mean? Scanner keyboardA = new Scanner(System.in);
The first part of the statement, Scanner keyboardA declares a variable named "keyboardA". The data type of the variable is Scanner. Because Scanner is a class, the keyboardA variable is a class type variable. Recall from our discussion on string objects that a class type variable holds the memory address of an object. Therefore, the keyboardA variable will be used to hold the address of a Scanner object. The second part of the statement is as follows: = new Scanner(System.in); The first thing we see in this part of the statement is the assignment operator (=). The assignment operator will assign something to the keyboardA variable. After the assignment operator we see the word "new", which is a Java key word. The purpose of the new key word is to create an object in memory. The type of object that will be created is listed next. In this case, we see Scanner(System.in) listed after the new key word. This specifies that a Scanner object should be created, and it should be connected to the System.in object. The memory address of the object is assigned (by the = operator) to the variable keyboard. After the statement executes, the keyboard variable will reference the Scanner object that was created in memory.
135
What methods does the scanner class have?
The Scanner class has methods for reading strings, bytes, integers, long integers, short integers, floats, and doubles.
136
What is the nextInt method?
The nextInt method formats an input value as an int, and then returns that value. Therefore, this statement formats the input that was entered at the keyboard as an int, and then returns it. The value is then assigned to the "number" variable.
137
What is important abou the import statement of the Scanner?
There is one last detail about the Scanner class that you must know before you will be ready to use it. The Scanner class is not automatically available to your Java programs. Any program that uses the Scanner class should have the following statement near the beginning of the file, before any class definition: * * import Java.util.Scanner; * This statement tells the Java compiler where in the Java library to find the scanner class, and makes it available to your program.
138
How do you read a character using the scanner?
Sometimes you will want to read a single character from the keyboard. For example, your program might ask the user a yes/no question, and specify that he or she type Y for yes or N for no. The Scanner class does not have a method for reading a single character, however. The approach that we will use for reading a character is to use the Scanner class's next Line method to read a string from the keyboard, and then use the String class's charAt method to extract the first character of the string. This will be the character that the user entered at the keyboard.
139
What does this mean? input = keyboard.nextLine(); answer = input.charAt(0);
The input variable references a String object. The last statement in this code calls the String class's charAt method to retrieve the character at position 0, which is the first character in the string. After this statement executes, the answer variable will hold the character that the user typed at the keyboard.
140
What happens when the user types keystrokes at the keyboard?
When the user types keystrokes at the keyboard, those keystrokes are stored in an area of memory that is sometimes called the keyboard buffer. Pressing the [Enter] key causes a newline character to be stored in the keyboard buffer. In the example running in the program above, the user was asked to enter his or her age, and the statement in line 27 called the nextInt method to read an integer from the keyboard buffer. Notice that the user entered a number and then pressed the [Enter] key. The nextInt method read the value from the keyboard buffer, and then stopped when it encountered the newline character. So the value was read from the keyboard buffer, but the newline character was not read. The newline character remained in the keyboard buffer. Next, the user was asked to enter his or her annual income. The user typed a value and then pressed the [Enter] key. When the nextDouble method in line 31 executed, it first encountered the newline character that was left behind by the nextInt method. This does not cause a problem because the nextDouble method is designed to skip any leading newline characters it encounters. It skips over the initial newline, reads the value of income from the keyboard buffer, and stops reading when it encounters the next newline character. This newline character is then left in the keyboard buffer. * Next, the user is asked to enter his or her name. In line 40 the nextLine method is called. The nextLine method, however, is not designed to skip over an initial newline character. If a newline character is the first character that the nextLine method encounters, then nothing will be read. Because the nextDouble method, back in line 31, left a newline character in the keyboard buffer, the nextLine method will not read any input. Instead, it will immediately terminate and the user will not be given a chance to enter his or her name. ***Makes a keyboard buffer issue because when trying to store a string after storing a double or int, the variable stores \n because you pressed enter so it won’t allow you to store anything (won’t print anything)
141
What is the solution to the keyboard buffer?
Notice that after the user's income is read by the nextDouble method in line 31, the nextLine method is called in line 34. (keyboard.nextLine();)The purpose of this call is to consume, or remove, the newline character that remains in the keyboard buffer. Then, in line 40, the nextLine method is called again. This time it correctly reads the user's name. Put this in between the storing of a double/int and a storing of a string to “consume” or “erase” the \n from the memory, allowing you to store a name with spaces Would also work by instead of storing the string with nextLine(), you store it with next() BUT then you won’t be able to have a string with a space (if you use a space, it will only read the characters before the space and will ignore the rest)
142
Before we use scanner class, what do we do?
Before we use the scanner class, we need to import it from the library -- in the Java library but we need to import using an import statement Put before the class header -- is grey right now but will turn a different colour when in use in source code import java.util.Scanner; ** you need to reference variable from the scanner class to allow methods to access the class as the scanner is like a tool box with objects Scanner jeyboard = new Scanner(System.in);
143
What does nextInt mean?
Look at keyboard input, parse it as an integer data type and assign it back to number1
144
What does keyboard.close() mean?
prevent memory leaks, where the Scanner reference variable keeps reading keyboard strokes
145
What is the JOptionPane Class?
The JOptionPane class allows you to quickly display a dialog box, which is a small graphical window displaying a message or requesting input.
146
What is a dialog box and the two types?
A dialog box is a small graphical window that displays a message to the user or requests input. You can quickly display dialog boxes with the JOptionPane class. There are two (2) types of boxes... Message Dialog: A dialog box that displays a message; an OK button is also displayed. Input Dialog: A dialog box that prompts the user for input and provides a text field where input is typed; an OK button and a Cancel button are also displayed
147
What does this mean? import javax.swing.JOptionPane;
The JOptionPane class is not automatically available to your Java programs. Any program that uses the JOptionPane class must have the following statement near the beginning of the file: import javax.swing.JOptionPane; This statement tells the compiler where to find the JOptionPane class and makes it available to your program.
148
What does this mean? JOptionPane.showMessageDialog(null, "Mr. Petti");
Displaying Message Dialogs: - The "showMessageDialog" method is used to display a message dialog. - The first argument (null) is only important in programs that display other graphical windows. - Until then, we will always pass the key word "null" as the first argument. This causes the dialog box to be displayed in the center of the screen. - The second argument is the message that we wish to display in the dialog box. This code will cause the dialog box to appear. When the user clicks the OK button, the dialog box will close. ALWAYS NEEDS TWO AGRUMENTS
149
What is the input dialog?
An input dialog is a quick and simple way to ask the user to enter data. You use the JOptionPane class's "showInputDialog" method to display an input dialog.
150
What does this mean? String name; name = JOptionPane.showInputDialog("Enter your name.");
- The argument passed to the method is a message to display in the dialog box. - This statement will cause the dialog box to be displayed in the center of the screen. - If the user clicks the OK button, "name" will reference the string value entered by the user into the text field. - If the user clicks the Cancel button, name will reference the special value null.
151
What does System.exit(0); mean?
- This statement causes the program to end, and is required if you use the JOptionPane class to display dialog boxes. Unlike a console program, a program that uses JOptionPane does not automatically stop executing when the end of the main method is reached, because the JOptionPane class causes an additional task to run in the JVM. - If the System.exit method is not called, this task, also known as a thread, will continue to execute, even after the end of the main method has been reached. - The System.exit method requires an integer argument. This argument is an exit code that is passed back to the operating system. Although this code is usually ignored, it can be used outside the program to indicate whether the program ended successfully or as a result of a failure. The value 0 traditionally indicates that the program ended successfully.
152
What does the showInputDialog method always return?
- Unlike the Scanner class, the JOptionPane class does not have different methods for reading values of different data types as input. - The showInputDialog method always returns the user's input as a String, even if the user enters numeric data. - For example, if the user enters the number 72 into an input dialog, the showInputDialog method will return the string "72". This can be a problem if you wish to use the users input in a math operation because, as you know, you cannot perform math on strings. - In such a case, you must convert the input to a numeric value. To convert a string value to a numeric value, you use one of the methods listed in below. Byte.parseByte --> Convert a String to a byte --> byte num; --> num = Byte.parseByte(str); | Double.parseDouble --> Convert a String to a double --> double num; --> num = Double.parseDouble(str); | Float.parseFloat ---> Convert a String to a float --> float num; --> num = Float.parseFloat(str); Integer.parselnt --> Convert a String to a integer --> int num; --> num = Integer.parseInt(str); Long.parseLong--> Convert a String to a long --> long num; --> num = Long.parseLong(str); Short.parseShort --> Convert a String to a short --> short num; --> num = Short.parseShort(str); |
153
How do you convert the value returned from the JOptionPane.showInputDialog method to an int?
int numberA; String strA; strA = JOptionPane.showInputDialog("Enter a number."); numberA = Integer.parseInt(strA); After this code executes, the number variable will hold the value entered by the user, converted to an int.
154
How you would you convert the user's input to a double using JOptionPane?
double price; String strB; strB = JOptionPane.showInputDialog("Enter the retail price."); price = Double.parseDouble(strB); After this code executes, the price variable will hold the value entered by the user, converted to a double.