Basics_Java Flashcards
Where do we put parameters for a function?
we use parameters to pass values to function

Where do we put the methods for our functions?
Inside the curly braces.
In Java the curly brace is on line with function name and return type

what is a good function (method name)?
clearly identifies the purpose of the function
camelCase notation
What is a function?
A block of code that performs a task
Think of buttons on a remote
In Java, functions are the smallest building blocks
Ex. functions to validate user info, convert weight to kgs
What is a package?
A concept for grouping related classes.
We will have hundreds or thousands of classes.
We should organize these classes into packages.
Java creates a namespace for our classes:
com.namespace
*every class we create in our program will belong to this package

Where do we specify a return type?
A function is a block of code that performs some task.
We specify the return type before the name.
Some functions don’t return anything.

Where is the entry point into our program?
Every Java program must have one function.
The main function is executed first.

What is a class?
A container for related functions.
We use classes to organize our code.
Ex. The supermarket has related products in different “classes” or sections.
What class must every Java program have?
Every program in Java has a main class that contains the main function.

What is a method?
A method is a function that is part of a class
What is an access modifier?
A special keyword that determines if other classes and methods can access these classes and methods.
Private
Public

What is the naming convention for classes and methods?

What are the two steps involved in running a Java program?

How do we get byte code?
Java Compiler changes our source code into byte code

Who developed Java?
At Sun Microsystems.
Sun Microsystems was later acquired by Oracle in 2010.
It was originally called Oak named after the tree outside Goslings office.

Where can our Java byte code run?
Java byte code is platform-independent
It can run on Linux, mac, windows or any operating systems that have a Java Run-Time Environment
What is java byte code?
The instruction set for the Java Virtual Machine
Assembled code is runnable on a CPU with a specific instruction set, while bytecode can be executed in a virtual machine (such as the Java runtime) on any CPU that can run the VM. Assembly code is (represents) the native code for the processor you are programming.

What is a Java Run Time Environment?
The Java Runtime environment has a component called Java Virtual Machine (JVM)
JVM translates our byte code into the native executable language for various platforms (Mac, Windows, Linux)

What is byte code?

What does the Java Virtual Machine (JVM) perform?
Converts our Java Byte code into the native code for the operating system we are using like a mac, windows or linux operating system.
This makes applications portable.
Can execute on Linux, Mac or any other operating systems that have a Java Run-Time Environment.

Who owns Java?
Oracle
Oracle Corporation is the current owner of the official implementation of the Java SE platform, following their acquisition of Sun Microsystems on January 27, 2010.
How many editions are there of Java?
Four Editions for different types of applications
SE - all the libraries all Java developers must learn
EE - provides additional libraries for building fault-tolerant multi distributed systems
ME - libraries specific for mobile phones
Java Card - for smart cards

How many worldwide developers does Java have?
9 million developers world wide

How many mobile phones run Java?
3 billion mobile phones currently run Java
What is JDK?
Java Development Kit
Software Development Environment
Compiler
Reusable Code
Java Run Time Environment

How many TV sets run Java?
120 Million TV sets
Every blue-ray device
What is JVM?
The JVM has two primary functions:
to allow Java programs to run on any device or operating system (known as the “Write once, run anywhere” principle), and
to manage and optimize program memory.
When Java was released in 1995, all computer programs were written to a specific operating system, and program memory was managed by the software developer. So the JVM was a revelation.
What is the average US salary for a Java developer?
$101,929 USD
Java is everywhere.
There are many opportunities to get hired as a professional Java developer.

What topics does this course include?
Build clean code
Fix bugs and errors
Understand types
Create algorithms
Package and deploy programs so other people can use them!

What’s included in types?
Variables and Constants
Primitive and Reference Types
Casting
Numbers, Strings and Arrays
Reading Input

What is a variable?
A variable is how we temporarily store data in computer memory.
What is an identifier?
The name of a variable
”=” is assignment operator
What can we do with variables?
Copy the value of one into another

What is the naming convention for variables?
Camel case!
lowercase first letter Uppercase other letters!
Ex. int herAge = 30
What are the two types in Java?

What are the primitive types in Java?
int - allow us to store values up to 2 billion
long - store numbers greater than 2 billion
double - storing values with decimal values
float - storing values decimal values
char - storing characters
boolean - store true or false

What is best practice for variables?
always use meaningful, descriptive names
What must we do to a long type in Java?
add and L after the value.
By default Java compiler recognizes a number as an integer.
Put an L after to tell Java compiler its a long!

What must we do to use a float type?
Java see’s numbers with decimals as doubles by default.
We have to add a suffix to represent the number as a float
Add “F”

How do we initialize a char type?
surround single characters by single quotes
string represents a series of characters

What are reference types?
objects + their members (data/functions)

What is casting?
Type conversion
How do we initialize reference types (objects)?
use the new operator
Allocate memory

How will Java execute this statement?

First, allocate some memory to store the point object
Next, allocate a separate part in memory to store a reference (the address) to the point object
Finally, assign this reference to the variable name
How are primitive types stored in memory?
Value is stored in the variable at that memory location
x and y are completely independent of each other

What are we copying into pointTwo in this expression?

The reference to pointOne object in memory, not the point object
What is the crucial difference between how primitive and reference types are stored in memory?
When we declare a primitive variable like a byte the value we assign is stored in that memory location.
When we use a reference type our variable holds the reference (address) of the object in memory not the actual value.

How does Java store reference types in memory?
Variable holds the address or reference of the object in memory, not the actual value.
Two variables can reference the same object.

What should we remember about the differences between primitive and reference types?
Remember,
reference types are copied by references.
primitives are copied by values and are completed independent of each other.
What are strings in Java?
Strings are reference types.
We use a short way to create them (can omit the new operator)
Strings are a class so we can access methods with the dot operator!
What can we do with strings?
because strings are a class,
we can access methods like ends with, length, indexOf(), replace etc.
Ex. check length of user input string
Ex. give the index of the first character

What is the difference between parameters and arguments?
parameters are the holes we define in our methods.
arguments are actual values we pass to these methods.
What are strings in Java?
Immutable
We cannot mutate them, we cannot change them
any methods that modify a string create a new string object
What is a useful string method in Java?
the trim method
used if a user types unnecessary white spaces in form fields

What don’t primitive types have?
Members
properties (data) or functions
What is an object?
An instance of a class
A reference type
object/classes have members we can access using the dot operator

What type are arrays?
Reference types
We need the new operator
we can access elements or items in the array via an index

By default, when we print an array what does Java return?
Java returns the string of the address in memory
to see the actual items in the array we must use the array’s class
What is a shortcut for generating
System.out.println()
?
“sout” + Tab
How many bytes are used in primitive types?

How can we initialize string objects in Java?
String is a reference type however, we have a shortcut
Can omit the new operator
JavaRuntime will handle

How do we return the string representation of an array?
Use the array class .toString method
there is a .toString for every primitive type

What two categories of types in java?

What is one of the differences between the primitive and reference types in java?
Reference types use the new operator to allocate memory for the reference variable
Primitive types don’t require us to allocate memory java run time environment does this for us!

What are the four most common String escape sequences?
" = "fileNames"
\n = new line
**** = \
\t = tab

What is a modern syntax for initializing an array when you know the values ahead of time?

What do we use arrays to do?
Store a list of items:
numbers
people
message
Describe the Arrays class in Java?
Defined in Java.util
Has useful methods:
Arrays.toString

What can we create in Java?
Multi-dimensional array’s
Can create a 2D array to store a matrix
or a 3D array to store data for a cube
These are useful for scientific computations
Ex. two rows and three columns

What is the convention for naming constants?
all CAPS
add the final

What arithmetic operators do we have in Java?
All the same in math like “+” “-“ “*” “/”and “%” (modulus or remainder)
/ gives a whole number
What is method overloading?
In Java.util package
Arrays Class
Arrays.toString method - returns string rep of array
defined for all primitive types
What is an expression?
A piece of code that produces a value
How can we execute a division to produce a decimal result?
s are called operands
By default Java returns integer values for integer division.
Cast our input into double

What must we do when using division?
cast the numbers into a double

What is the incrememnt operator?
if we want to increment a value
we can add ++
Can say ++x (prefix) OR x++ (suffix) same value

What is the x, y and j values be in this expression using increment operator?


What will the value of x and y by using the increment operator (prefix) in this expression?

First, Java will increment x by one x (=2)
Then, Java will copy x value to y (=2)

How can we declare a constant in Java?
add final keyword
cannot change value later in program

What will the value of x and y by using the increment operator as a suffix in this expression?

First, Java assigns the value of x (=1) to y
Then, increments x by one x (=2)

What happens when we use the increment operation after the assignment operator?
if increment as a suffix x++
first value of x is copied to y
then x is incremented by 1
if increment as a prefix ++x
first, x is incremented by 1
then copied to y

What is the augmented (compound) assignment operator?
We can increment by 2
x+=2 will increment x by 2 and copy into x

What are the order of operations in Java
If we want a value calculated first,
we can put it in parentheses.

What is implicit casting?
Automatic casting / automatic conversion
Java allocates an anonymous variable in memory
that variable is another primitive type (byte, int, long)
Java copies value into this new anonymous variable
If the value can be converted into a bigger type, Java automatically does this for us.
short = two bytes
int = four bytes

When does implicit data casting happen?
when there is no change for data loss
when we are going from a smaller to a larger data type

What is explicit casting?
convert x to an integer w/o decimal point
x will be added to 2 result = 3

When can explicit casting only happen?
between compatible types
all number types
cannot cast a string to a number
What are wrapper classes?
For all primitive types, have wrapper classes
reference type defined in java.lang
reference classes have methods
like parseInt() which takes a string returns a short or int

Why does casting matter?
in most GUI data from the user is received as a string!
If we have text boxes or drop down lists almost always we receive data as strings
we must convert these strings to numerical representatives
What does the Math.max class return?
The greater of two values

How to comment out a block of code in Java?
Control + Shift + /

What is the Math.random ( ) method return?
A random number (float)
to set between a value, multiple by range

How can we explicitly cast and round a random number?
pass the random method as an argument to the round method
explicitly cast the value into an integer

How can we input data in Java?
use the scanner class
Java will do implicit casting to make the int value of age into a string and concatenate

What is the shortcut for renaming a variable?
Shift + F6
How can we read a string using the scanner class?
using the scanner.next ( ) method

How do we read the whole line using the scanner method?
use the scanner.nextLine ( )

What is the shortcut for renaming a variable?
Shift + F6
How can we chain multiple methods to remove whitespace when reading a string in Java?
use the dot operator to access members (methods) of the string object
call the trim method
then store value in the name variable

How to implement a mortgage calculator?
First attempt
No input validation
Written as procedural code

What is control flow?
controlling the flow of execution of our programs
What is control flow?
controlling the flow of execution
Why do we use loops?
executing code repetitively
Ex.
For loops
For each
While loops
Do-while
What is covered in this section?
Comparison operators
comparing values
Ex.
>= <= ==
Logical operators
implementing real-world rules
Ex.
&& != ||
Conditional statements
making decisions around code execution in our programs
Ex.
If, switch statements
Loops
executing code repetitively
Ex.
for, while loops

What are comparison operators?
Used for comparing values
greater than
equal to
less than
>=
<=
==
When do we use comparison operators?
To compare primitive values
Ex. is x and y the same?
What is the equality operator?
a boolean expression
returns true/false
represented with two equal signs “==”

What is the inequality operator?
A boolean expression
!=
returns a true/false

Why do we use conditional statements?
Making decisions in our programs
Ex. If statements
What are other equality operators?
>=
(greater than or equal)
<=
(less than or equal)
These return boolean (true/false) values

How does Java evaluate && logical operator?
Evaluates from left to right
First, it looks at the leftmost condition
if false, doesn’t look at other conditions, returns false

What do we use logical operators for?
Implementing real-world rules
& || !
What does a single “=” mean?
the assignment operator
we use it to assign a value to a variable
When is the || operator true?
The or || operator is true if at least one condition is true.

When do we use the NOT operator?
To reverse a value
if the value hasCriminalRecord = false;
!hasCriminalRecord returns true

What is a clean way to simplify an if statement?
use a boolean operator
wrap in ( ) to be clear

How can we reformat our if-statement so it’s easier to read?
Remove { } braces from single statement clauses
put else if on the line below ending curly brace ( { )

What’s the problem with declaring a variable in our if-statement?
It’s only available within that code block
we cannot access outside

How can we read data from the user?
Use the Scanner class!
Read from the console:
new Scanner (System.in)

How do we implement an if statement?
If statement
three clauses
look at format
Hierarchy
parent w/ two children
} else if (condition)
} else

Why are if statements extremely powerful?
They allow build programs to make decisions based on certain conditions?
Ex. Printing messages on console based on certain conditions

What do we type inside the brackets after an if statements?
A boolean value
if the condition is true, the statements in curly braces are executed.
What is a clause in an if statement?
a section
parent and children hierarchy
If only one line of code in the if statement can omit the { }
Technically, people say always have { }

What is the problem with this if statement?
The variable hasHighIncome is only available within the curly braces!

What is one way we can solve the issue of only being able to access a variable within curly braces?
Declare the variable outside the if-statement
set the value to true within the statement
**this code look amateurish

How can we improve out if-statement?
we can set the variable to an initial value.
Or
we can set our variable to an expression and eliminate the if-statement entirely
if the expression is true it will evaluate to true, otherwise it will evaluate to false.

Why does Mosh wrap the right side of the expression in parentheses?
To make it more clear
now it’s clear that on the right side of the assignment operator we have a boolean expression

What kind of code doesn’t a professional programmer write?
This kind.
One way to fix this is give the variable an initial value
This can be simplified even further using a ternary operator!

How do we use the ternary operator?
Condition (boolean expression)? value #1 : value #2
We start with our condition
then we add a “?”
if the first condition is true, value after “?” is assigned
otherwise the value after “:” is assigned
String className = income > 100_000 ? “first” : “economy”

When do we use switch statements?
To execute different parts of code depending on the value of the expression.
like an if-statement

Why do we add a “break” statement to our switch statement?
Java will continue to execute the other cases
once it evaluates a break statement it jumps out of the switch statement
How do we implement a switch-statement?
add a break after each case
default will execute if no cases are met
What’s the correct solution to FizzBuzz?

How do we implement the FizzBuzz method?
Put the most specific statements on top
Java evaluates top to bottom

What’s the trade-off with this implementation of FizzBuzz?
It has a nested structure.
Mosh prefers a flat structure.
Additional nested structures make the code hard to read

What three things do we do inside the ( ) of a for loop?
- Declare a counter variable ( i , j , k) - loop counters
- Declare a boolean expression - declare how long loop is executed
- Increment loop counter
*If a single expression, don’t need curly braces but if multiple statements must declare a code block

How does Java execute a for loop?
- first it initializes i to zero (first statement)
- Then it evaluates the boolean (if true, executes code block)
- At end of loop, control moves to increment i to ++

How can we implement a for loop using the decrement operator?
Output:
Hello World 5
Hello World 4
Hello World 3
Hello World 2
Hello World 1

How does the ternary operator work?
start with a condition
if the condition is true, evaluate and assign value after “?”
otherwise, if the condition is false, evaluate and assign value after “ : “

Why is this not the right solution for FizzBuzz?
Because of the way Java executes the if statement
Sequentially executes
Put most complex case first
Simpler cases follow

What is the basic syntax for a while loop?
initialize a loop variable
set a condition for termination
execute code in the block
decrement the counter variable

When should we use a for loop vs. while loop?
For Loop:
We know how many times we want to execute one or more statements
While Loop:
We don’t know exactly how long to execute
How can we write a while loop to continuously ask a user to enter something until they write quit?

What are Do..while loops?
Similar to while loops
Gets executed at least once
the condition gets checked last

What is the syntax for a do-while loop?

While loops vs. Do…While loops?
While loops
check conditions first, if false it never gets executed.
do..While loops
we check the condition last!
Do…while loops are rare and we often use while loops!
How does Java execute the break statement?
it ignores everything after and break statement and exits out of the loop.

What is an example of a for loop?
Set counter to count down or count up!

What is the continue statement in a while loop?
Java sees the continue statement
moves the control to the beginning of the loop
all statements after are ignored

What is a common technique used by professional developers when writing while statements?
set the while condition to (true)
the loop is executed forever until the break condition is met!
make sure to use a break statement otherwise, you have an infinite loop!

What must we include when writing always true while statements?
while (true)
include a break statement!
otherwise, you have an infinite loop!
What is the basic structure of a for loop?
use “for” keyword
a counter variable and initialize
boolean expression determines how many times loop is executed
increment the counter variable

When do we use For-Each loops?
When iterating over an array or collection!
Replaces a for loop
we don’t have to write a numeric counter
we don’t have to write a boolean expression
we don’t have to increment our counter
How do we declare a for-each loop?
inside for ( )
include the type of array (collection) we are iterating over
declare a variable to hold the value of each item one at a time in our collection per iteration.
Ex.

What are the limitations of for-each loops?
For each loop:
- Forward only - Cannot iterate end to the beginning.
- Don’t have access to index - loop variable stores only one item
For Loop:
can access values by index

How can we iterate over an array backwards using a for ( ) loop?
Set the counter variable to length of the array
as long as i is greater than 0
print value at the index of counter
decrement counter

How can we implement a while loop to handle error validation in our mortgage calculator?
Initialize the variables to zero outside the loops!

What separates an outstanding programmer from an average programmer?
Knowing how to write good code:
Code that is clean and expressive
What does Martin Fowler say about clean coding?
Mosh puts a lot of emphasis on clean code!

What is Mosh going to show us in this section?
The most important techniques for writing clean code.
What is a parameter variable just like?
It’s just the same as if we declared a local variable inside
it’s like a local variable inside the method

How do we create a method?
camelCase for method name and parameters
parameter is like a local variable inside the method

How do we create a method that returns a value?
Change return type
call the method from the main class
Give it an argument
store the return value in a variable

What is the syntax for multiple method parameters?
cameCase for parameter identifiers
separate with a comma

How do we return a value from our method?
Change return type from void to String
return keyword to return value
*when calling this method can store the return value in a variable

What is refactoring?
Changing the structure of our code without changing its behavior.
Extracting certain methods and putting them in other methods.
Extracting methods
Refactoring Repetitive Patterns

When refactoring, what two things should we look for?
- Look for conceptually close code - lines of code that always go together. Bring lines together into a separate private method. Can re-use method in the future!
- Repetitive patterns in code - code that uses repetitive loops asking the same questions using similar patterns
How long should our ideal methods be?
5-10 lines of code!
No more than 20 lines!
How can we extract a method for calculating the mortgage?
Create a method for calculating mortgage
Call this method in the main class

How can we extract code into a method using an Intellij shortcut?
Right-click the lines
Select Refactor
Select Extract
Choose Method

How can we refactor these repetitive loops?

Create a readNumber method!

What debugging and deploying application topics are covered?

What are compile-time errors?
Syntax errors.
Prevent us from compiling our applications.
Happen when we don’t follow grammar or syntax of Java.
Easy to find and fix!
What is a great resource for a syntax error you don’t know?
Stackoverflow.com!
Professional programmers and enthusiasts!
Search for error message 99% of time you can find a page on this error!
How can we find run time errors?
Debugger!
Execute our code line by line.
Look at the value of various variables!
What are the two types of errors?
Compile-time: syntax or grammar errors, use IntelliJ or StackOverflow
Run-time errors: use Debugger to look at variables

What are the common compile-time errors?
- Forget to specify the data type of variables
- Forget to add a semi-colon to the end of statements!
- Call a method without using ( )
- Print a string without double quotes
- misspell or incorrectly capitalize a variable name (Java is case sensitive)
- using reserve keywords for identifiers
- using a single “=” to compare values”==”
Do you have to pay to use Java?
Yes and No.
No, it’s open-source.
Yes, there are additional features/support you can pay to use.

What is the call stack in the debugger?
An area where we can see all the methods that were executed in reverse order!
Useful for debugging large applications!
Can set a breakpoint and watch all the methods to get there!

What are watches in the debugger?
can set watches to view specific variable values

What does deploying web or mobile apps require?
Additional steps outside the scope of this course.
What is a module?
Another layer of abstraction above packages
What must we do if we want to share our Java program (console program) with someone else?
need to package it into a .jar file
Java Archive - contains all code for distribution
Anyone with Java Run Time environment can run it
How do we generate a .jar file in IntelliJ?
File -> Project Structure -> Artifacts

Build -> build artifacts
What is the IntelliJ shortcut for multi-cursor editing?
Option (press) + option (hold) + down arrow
