Basics of Java Flashcards
What is Java?
a programming language that allows you to provide instructions to a computer, and with which you can create computer programs
Java compiler
translates Java code into machine or computer language so the computer can execute the program
How to delineate a single line and multi line comment?
single line comment //
multi line comment /…/
How to name the program?
class Main {…}
tells Java the name of the program is Main
What is the main method?
static public void main (String[] args)
this statement is called the main method and should be included in every Java program. Tells the compiler this is the beginning of the Java program. ‘public’ and ‘static’ can be interchanged.
Is syntax important in Java?
proper syntax is essential or the program will not run.
What is an executable statement?
code that produces output
statements in Java must end with a semicolon;
What does public mean in
static public void main (String[] args)
means that any object can use the main method
What does static mean in
static public void main (String[] args)
means that the main method is a class method, also means you can access this method without having an instance of the class
What does void mean in
static public void main (String[] args)
tells Java the main method won’t return a value. Other methods in other classes can receive and return values/variables, but main cannot return anything
What does main mean in
static public void main (String[] args)
the main method is responsible for calling any other methods within the program. This is the first thing the compiler looks for in the program.
What does string args in
static public void main (String[] args)
sets up the main method to accept parameters, once packaged and distributed users can specify arguments to pass to the main function
What is one argument the main method takes?
an array of string elements
(String[] args)
What does args do in
static public void main (String[] args)
holds the actual parameters passed in
What are java statements?
instructions that tell the programming language what to do
What is an assignment statement?
assigns a value to a variable
What is a Java method?
blocks of code that perform a task and can be used by other parts of a computer program such as a declaration statement.
What are the core Java statements that end in curly brackets instead or semicolon?
if statement
while statement
for loop statement
What is the difference between rules and conventions in Java?
Rules are hard and fast: your program won’t compile or run if you violate the rule. Conventions are practices that most Java programmers follow.
What are keywords?
words that have a predefined meaning for the language
Rules of naming variables:
- variables are case sensitive
- cannot be Java keywords
- main/Main is not a keyword in Java
- no spaces in variable names
Naming conventions for constants:
- convention: use uppercase with underscore
final FIRST_NAME = “Sandy”; - rule: constant names cannot be Java keywords
- rule: constants cannot have spaces
Naming convention for classes and interfaces:
Capitalized nouns, each word capitalized
Employee, UnionEmployee, Remote
Naming convention for methods:
lowercase verbs
public void enterData() {}
Naming conventions for variables:
short and meaningful
int[] counter, double fees;
Naming conventions for constants:
all uppercase
universe = ALL;
Naming conventions for packages:
all lowercase letters
java.util.*;
Describe the short data type:
smallest type at only two bytes (16 bits)
It accepts values from -32,768 to 32,767
it’s signed, meaning it accepts both negative and positive values
short is used more for lower-level programming, such as image processing or working with sound processing
Describe the int data type:
consumes 32 bits in memory, is a whole number
the valid number range is:
-2,147,483,648 to 2,147,483,647
Describe the long data type:
64 bits of memory and accepts a range from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
It’s useful for storing numbers that outgrow the integer data type.
Describe float data type:
A float data type is a single precision number format that occupies 4 bytes or 32 bits in computer memory
A float data type in Java stores a decimal value with 6-7 total digits of precision. So, for example, 12.12345 can be saved as a float, but 12.123456789 can’t be saved as a float
default value is 0.0f
Describe double data type:
A double data type is a double precision number format that occupies 8 bytes or 64 bits in the memory of a computer.
The double data type stores decimal values with 15-16 digits of precision
default value is 0.0d
Describe the char data type:
char is short for character, 16 bits in size, single character, can be specified via unicode ie. 7 7=M or with single quotes ‘M’
What is unicode?
Unicode is a computer encoding methodology that assigns a unique number for every character.
65=A
66=B
67=C…..
Describe the Java string data type:
a sequence of single characters, a string is also a class, which means that it has its own methods for working on strings.
Because a string is a class, when we declare a string, we are creating an instance of that class. Therefore, the keyword new is used to create a new instance
length()
outputs the length of the string in number of characters
toUpperCase()
toLowerCase()
output string to all upper case or lower case
trim()
output removes all spaces in the string
replace()
replace all instances of a certain character sequence with another
Java escape codes
" double quote
\ backslash
\t tab
\n new line
Concatenation
adding strings together
String hello = new String(“Hello World!”);
String niceDay = new String(“It’s a nice day!”);
String output = hello + “ “ + niceDay;
output= Hello World! It’s a nice day!
Describe Java boolean data type:
a primitive data type, true or false, defaults to false
What are the Java primitive data types in order from smallest to largest?
1 bit - boolean
8 bit - byte
16 bit - char, short
32 bit - int, float
64 bit - long, double
What are the two type of data conversion?
Implicit conversion- moving a number from a smaller data type into a larger data type (one with more bits of storage), no information will be lost.
byte->short->int->long->float->double
‘char’ and ‘boolean’ data type are not eligible for implicit conversion
Explicit conversion- when choice does not allow, one must move one data type to another type of narrower size(one with fewer bits of storage). Truncation may be necessary. An error will be cast.
A type cast must be used to force Java to move the value explicitly.
What is a type cast?
A wider data type can be explicitly cast to a narrower type by enclosing the narrower data type name in parentheses and placing it in front of the variable declared with the wider data type.
Describe byte data type:
8-bit signed Java primitive integer data type. Its range is -128 to 127 (-27 to 27 - 1).
byte type is the smallest integer data type available in Java.
In what order does Java perform math operations?
The same order of operations as math does
PEMDAS
Java math operators:
+ addition
- subtraction
* multiplication
/ division
% modulo (returns the remainder of the division between two numbers)
What are relational operators?
They help us check if a condition is met by answering questions.
==
checking to see if the two values are equal to each other
careful!!! not using these correctly i.e. = instead of == will result in an assignment error and actually assign a value instead of comparing a value.
!=
not equal to
> ,<
less than or greater than
> =
greater than or equal to
<=
less than or equal to
Boolean operators
AND and OR lets us combine these relational operators to ask questions, such as did the employee work more than 40 AND less than 60 hours this week.
&&
AND
||
OR
What are API’s in Java?
API stands for Application Programming Interface. In Java-speak, the APIs are a collection of packages that programmers can import into their programs.
What is a package in Java?
Inside each package there are interfaces, classes, methods, fields, and constructors.
There is a lot of functionality in these packages.
How to input the Scanner class from the Java util package?
import java.util.Scanner;
What does pseudorandom mean?
that the actual bits underneath the hood are not moved around in an equal manner.
nextInt(int n)
a method that generates a pseudorandom number from the Random class
Java if statement:
if(Boolean_expression) {
// Anything here will be executed if the expression is true
}
What is the correct way to see if the String object s1 equals “green”
if(s1.equals(“green”)) { }
Recall that the Java String object has a method called equals(), and you place what you are comparing between the parentheses of that method.
What are the three things a Java program should always. have?
main method
class
some comments
conditional statement not necessary
What is a switch statement in Java?
In Java, the switch statement evaluates the expression, and then goes to a position within the switch statement based on that value.
Data types that cannot be evaluated: doubles or floats.
Specific case statements are processed based on that value. If none of the statements match, a default option is required for any fallout.
Describe a while loop:
A while statement performs an action until a certain criteria is false. This condition uses a boolean. The code will keep on processing as long as that value is true.
What is an indefinite loop?
A type of while loop where you don’t know when the condition will be true.
A while loop runs code as long as the conditions is/are?
The loop will continue as long as the value is true; once they are false the condition will stop.
Describe a for loop:
A for loop is a counting loop, because it repeats a set of instructions for a set number of times. For loops are useful when you know when the condition will be met.
for (initial start point; stop conditon; amount to increment) {
instructions/code here;
}
Nested for loops:
a for loop within a for loop
nested for loops are usually declared with the help of counter variables, conventionally declared as i, j, k, and so on, for each nested loop
For each loop:
used mainly for looping through collections
How many times will the nested loop run?
for (int i=1; i<=3; i++) {
for (int j=1; j<=i; j++) {
}
}
The nested loop will run at least once for each pass through the main loop. When i is 1, j will run once; When i is 2, j will run twice (since it is set to run as many times as the value of i); when i is 3, j will run three times; for a total of six.
What is the problem with this code?
for (int i=1; i<=3; i++) {
for (int j=1; i<=3; j++) {
}
}
It could run indefinitely
Nested while loop:
a while statement inside another while statement. In a nested while loop, one iteration of the outer loop is first executed, after which the inner loop is executed. The execution of the inner loop continues till the condition described in the inner loop is satisfied. Once the condition of the inner loop is satisfied, the program moves to th
In the code below what gets printed after 2 : 5?
class Main {
public static void main(String args[]) {
int outerLoop = 2;
while(outerLoop <5) {
int innerLoop = 4; while(innerLoop < 7) { System.out.println(outerLoop + ': ' + innerLoop); innerLoop++;
}
outerLoop++;
}
}
}
2:6
import java.util.*;
public class Main {
public static void main(String args[]) {
int outerLoop = 3;
while (outerLoop < 8) {
int innerLoop = 5;
while(innerLoop < 7) {
if(innerLoop == 6) { break; } else { System.out.println(outerLoop + ":" + innerLoop); innerLoop++; }
outerLoop++;
}
}
}
}
Here the inner loop breaks at 6. So it prints only till 5. The outer loop starts at 3 and prints 3 : 5. The next iteration of the inner loop is 6, but at this point the inner loop breaks. So the execution goes to the next iteration of the outer loop 4 and the inner loop 5, and prints 4 : 5.
In a nested while loop what happens if there is a break in the inner loop?
A break statement in an inner loop causes the inner loop to stop execution if the condition in the break statement is satisfied.
What are the branching statements in Java?
break, continue, return
Uses of the break statement:
allows the user to return to the main
if some condition is met during processing
Uses of the continue statement:
If inside a ‘while’, ‘do’, or ‘for’ loop. There is also a break statement within the code. If we DON’T want to stop at that point, but stop the current iteration and continue to the next, we need a continue statement.
What does the Java return statement do?
The return statement sends control back to a constructor or method, effectively giving the keys back to the original driver.
Describe do-while loop:
runs while a specific condition is false
do {
//commands
}
while (condition);
What happens if there is a possibility that the condition will never be met?
you created an infinite loop and will have to terminate the program
Examine the following code. What is missing?
do {
//instructions
}while(true)
semicolon at the end of the while statement
What is an infinite while loop in Java?
a set of code that would repeat itself forever, unless the system crashes. At a certain point the program will overflow and fail.
Choosing between switch and if-else statements?
One common reason for choosing switch over if statements is when there are a large number of possible scenarios.
Switch makes the code a lot more readable and traceable in the debugging process.
One classic example wherein a decision has to be made by checking (testing) an expression based on a range of values or conditions, switch cannot be used. This is because a switch statement can test expressions based on only on single (permissible) primitive data-type value, a single enumerated value, or a single String object.
What is an array?
an array is simply a sequence of values, where each item is the same data type.
an array is a single object, even though it is made up of a number of pieces.
What is the most common way to step through an array?
using a for loop
for(int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
//print out each block in the sequence
}
A Java array that would have rows and columns is called a _____ array?
two-dimensional
default array initialization
default array initialization
int[] highScores = new int[5];
Examine the following code for an array.
long [] phoneNumber;
Write a statement to initialize it:
phoneNumber = new long[55];
What is a multidimensional array?
an array within an array
How to create a table of integers that is 5 by 5 and provide the data to fill the table?
table = new int [5] [5];
int [][] table = {
{395,830,137,450,949,
446,610,636,818,22,
807,337,187,812,236,
546,772,699,867,216,
340,814,815,88,483}
};
}
What is a dynamic array?
an array that can grow and shrink as needed.
What is an ArrayList?
provides several methods for working with arrays, including adding, updating the index/buckets, and removing elements. Instead of the length option, ArrayList has the size feature.
What is a constructor?
used to initialize an instance of our class
Java array length vs size:
Length of an array is the number of elements in the array.
Size applies to ArrayList collection object, not Java arrays.
What is a matrix?
A table of numbers arranged in rows and columns.
How to multiply matrices:
Multiplying matrices in Java involves the creation of 2-dimensional arrays and nested for loops to traverse through the matrices and complete the math. When multiplying a matrix, you start at the first row of the first matrix, and down the first column of the second, and then repeating for all for the rest of the values. Each pair (row/column) is multiplied and then added to the total for that row/column pair, known as the dot product.
In order for matrix multiplication to work, the number of _____ in the first matrix must match the number of _____ in the second matrix.
Columns, rows
After completing the matrix multiplication, the resulting matrix will have the same number of _____ as the first matrix, and the same number of _____ as the second matrix.
Rows, columns
When multiplying matrices, we start at the first _____ of the first matrix and the first _____ of the second.
row, column
What is an ArrayList?
an array that we can add and/or subtract from.
What does this code do?
ArrayList <String> employees = new ArrayList <String>(5);</String></String>
declares an instance of the ArrayList class and calls it employess
If it is possible that a get method will try to reach a non-existent index, what should you do?
Place the get method within a try statement, and catch the error in a catch statement
What is a command line?
A command-line interface is a text-based console, such as the Windows command prompt or the Unix/Linux shell window where you type in all your commands.
The main method’s parameter, args, allows passing which of the following?
Arguments are stored in a string array and can be converted by the main method to whatever data types it expects.
When the main method parses the input parameters, it stores the largest numbers first.
False, The arguments are stored as strings in the parameter args in the order in which they are passed in.
Which of the java commands will compile java files from the command-line prompt?
javac
The main method’s parameter, args, allows passing what?
Multiple arguments separated by space.
how to import Java Scanner?
import java.util.Scanner;
Code to prompt user to enter a number when they did not enter a number?
while (!enterQty.hasNextInt()) {
System.out.println(“Enter Integer”);
enterQty.next();
}
Examine the following code. What is true about the variable inputValue?
Scanner inputValue = new Scanner(System.in);
It is an instance of the scanner class
What is BufferedReader?
reads text from an input stream, but it buffers the data to provide more efficiency, can be used in a multi threaded program unlike the Scanner class.
Differences between Scanner and BufferedReader:
Scanner can check for a specific data type and convert it to a specific data type as our data is obtained from the stream.
BufferedReader is synchronous whereas Scanner is not, so BufferedReader can be shared across multiple threads whereas Scanner cannot
BufferedReader has a bigger default buffer than Scanner 8KB vs 1KB
When using the Scanner class to read data from the console, in order to read data which is a double and assign it directly to a double variable you can use the method:
nextDouble()
The correct answer is ‘nextDouble()’ which will obtain the next value and convert it to double data type and return it as such.
Which is the correct way to specify input from the console using the BufferedReader constructor?
BufferedReader(new InputStreamReader(System.in))
because the constructor takes Reader as a parameter and System.in specifies the standard input stream.
When using the Scanner class to read data from the console, if the nextInt() method is used but the value in the stream is not an integer but a character, the method will:
Throw InputMatchException
If we cannot be sure of the input in the stream we can use the hasX methods first to check what the data type of the next data is.
The top, abstract class in Java to represent an input stream of bytes is _____.
InputStream.
The Scanner class (package java.util.Scanner) is a text scanner that breaks up input into _____.
tokens
Explanation
The Scanner class (package java.util.Scanner) is a text scanner that breaks up input into tokens based on a delimiter pattern such as space (default), semi-colon, tab, etc.
What is the standard output?
The standard output in Java is the PrintStream class accessed through the System.out field. By default, standard output prints to the display, also called the console.
Difference between:
System.out.print();
System.out.println();
println() will print the next value on the next line
\n
new line
“\n String”
\t
tab
“\t String”
How to print multiple types of data together?
Use a plus sign + to concatenate the data
String name = “Joe”;
int grade = 80;
System.out.println(“Student name: “ + name + “\nStudent grade: “ + grade);
The println() method in Java _____.
The correct answer is ‘terminates the line’. When the line is terminated, the cursor is moved to the next line.
What are the three attributes of the System class?
err (PrintStream)
for the standard error output stream
in (InputStream)
for the standard input stream
out (PrintStream)
for the standard output stream.
Describe the printf method:
System.out.printf
used for formatting the output of numbers and strings. The method takes the format string as the first parameter followed by a list of arguments that are to be formatted. The format string lets you specify the width, right/left justification, decimal precision, special sequences, and other formatting options.
What is PrintStream helpful for in standard out?
helps format the output
The System.out.printf method works exactly the same as the:
The correct answer is the format method. The behavior of both methods is identical. The term printf is the name of the standard out method in other languages so Java has it for convenience.
To print a floating point number with a precision of 4 decimal places, the correct format string for System.out.printf would be:
The correct answer is ‘’%.4f’’ where .4 specifies the precision and f specifies it is a floating point number.
To print an integer right justified with a width 15, the correct format string for System.out.printf method would be:
The correct answer is ‘‘%15d’’ where 15 specifies the width and since it is positive it is right justified and d specified integer
To print a floating point number with a precision of 2 and a width of 6, the correct format string for System.out.printf would be:
The correct answer is ‘‘%6.2f’’ where 6 specifies the width, .2 the precision, and f the floating point number.
What is a graphical user interface (GUI)?
uses visual elements that presents information stored in a computer in an easy to understand manner. These elements make it easy for people to work with and use computer software. A GUI uses windows, icons, and menus to carry out commands, such as opening files, deleting files and moving files. GUI software is much easier to use than command line software since there is no need to type in and memorize individual commands.
What does WIMP stand for?
window, icon, menu, and pointer
Define “usability”:
Usability is defined in an official ISO standard as ‘‘the extent to which a product can be used by specified users to achieve specified goals with effectiveness, efficiency, and satisfaction in a specified context of use.’’
How would you describe the use of a wizard in the context of computer software applications?
A wizard is part of a graphical user interface consisting of a series of pre-defined steps to implement a specific workflow.
You are developing a user interface for a software application. How would you proceed with this process?
You would perform user analysis, and collect functionality requirements.
Attributes of usability in a GUI:
Learnability: How easy is it for users to accomplish basic tasks?
Efficiency: How quickly can they perform tasks?
Memorability: How easily can users establish proficiency?
Errors: How many errors do users make?
Satisfaction: How pleasant is it to use the design?
What is a container used for?
A container is used to store the items the user will see on display, such as a panel or a frame (main window). These are the very core of what holds everything together and are the primary skeletal system of the GUI as a whole.
What are components used for in a GUI?
Components can be described as the add-ons or extensions to the containers that help to fill in the content and make up the rest of the user interface. Examples can include things such as a textbox, a button, a checkbox, or even a simple label.
What are the two classes of GUI in Java?
Abstract Window Toolkit (AWT) and Swing
What is AWT in Java GUI design?
The Abstract Window Toolkit is mostly the set of tools or programs that give a programmer the ability to create the components of the GUI itself, such as the buttons or scroll bars. They are known as the heavyweight components and are explicitly bound by the platform or operating system they are being used on.
What is Swing in Java GUI design?
Swing does the same thing as AWT, but as extensions to the AWT itself. These are known as the lightweight components and are entirely independent of the platform or operating system, which give them much more freedom and flexibility than the AWT.
When it comes to Java, a(n) _____ is used to fill up the rest of the container with content and can be called its extension.
Component
In order to create a polygon, what do you need to do first?
Polygon has its own class and you need to create a new instance of the Polygon class, and then set the points for each part of the shape.
How would you draw a rectangle that is a solid color?
g2.fillRect(10, 20, 100, 100);
If you were to create a rounded rectangle, which option correctly creates the shape?
Rounded rectangles include starting and ending x, y coordinates as well as the angle of the arc/sweep on the corners.
Which class allows you to set the thickness of a line?
g2.setStroke(new BasicStroke(5));
In the case of Swing, what is the container used for an application?
JFrame
Explain the difference between methods and constructors in JFrame:
Methods are functions that impact the JFrame such as size and visibility, constructors are run when the instance is created
You have created a new JFrame (jf) and added several other Swing elements. Which code statement correctly ensures that you will see your new GUI application on screen?
jf.setVisible(true);
Which of the following correctly creates a new JFrame without a title?
JFrame jf = new JFrame();
How can the text in a label component be changed?
Programatically at run time. Values of label components can only be changed programatically at run time.
How to create a JLabel with text?
JLabel jl = new JLabel(“New Label”);
When creating a JLabel that has an icon instead of text, what do you need to create first?
An instance of ImageIcon
In order to add a JLabel to a GUI application, which component is needed first?
JFrame
How would you change the text of a JLabel (lblUser) to “Enter User Name?”
lblUser.setText(“Enter User Name”);
What is it called when components are not manually laid out?
absolute positioning
Which containers form the base of the GUI application structure?
JPanel and content panes
Describe the Box Layout:
javax.swing.BoxLayout
This is a type of layout manager that allows multiple components to be laid out either vertically or horizontally. It does not allow any form of wrapping, hence, the vertical arrangement of components remains vertically arranged even when the frame is resized.
Describe the Group Layout:
javax.swing.GroupLayout
It works with vertical and horizontal layouts differently and each dimension is defined independently. And as a consequence, each component needs to be defined twice within the layout.
Describe the Scroll Pane Layout:
javax.swing.ScrollPaneLayout
This class is implemented as the layout manager used by JScrollPane and it is used by several components such as two scrollbars, a row header, a column header, a viewport and four corner components.
Describe the Spring Layout:
javax.swing.SpringLayout
This is a flexible layout manager that lets you specify precise relationships between the edges of components under its control. It designed for use by GUI builders.
The layout manager object is an implementation of which container?
layout manager interface
This method determines where an element will be displayed on the screen and its size:
setBounds
textBox.setBounds(x, y, height, width)
This is the syntax for setting the original starting position (x,y) and the height and width of a JTextField or JButton element.
As you are building a GUI application, you want to add a text entry field, but default it with some text. Which line of code achieves this task?
JTextField text1 = new JTextField(“[Enter User Name]”);
This command sets the text within the text box. This is not required but sometimes useful when building applications.
Tool tips are:
Methods
Tooltip, unlike JTextField and JButton, is not a class in Java. It is, rather, a functionality that is available to GUI components and is implemented as a method.
What JTextFields method is used for managing action events?
void addActionListener(ActionListener l)
is responsible for adding the specified action listener to receive action events from the text field.
Which of the following is required before adding text fields, labels, buttons, or tool tips?
JFrame
The very first task to perform in Java GUI programming is to create an object using the JFrame class.
What is an event in Java using Swing?
a user’s interaction with a component.
What is the event source?
The object that is triggered in the event.
What is an Event Listener?
Code that listens for changes, additions, user interaction, etc. When one of these actions is performed, it then does something based on that event.
What is an event object?
the event itself
ActionListener
Responds to actions (like a button click or text field change)
ItemListener
Listens for individual item changes (like a checkbox)
KeyListener
Listens for keyboard interaction
MouseListener
Listens for mouse events (like double-click, right-click, etc.)
MouseMotionListener
Listens for mouse motion
WindowListener
Acts on events in the window
ContainerListener
Listens for container (like JFrame or JPanel) events
ComponentListener
Listens for changes to components (like a label being moved, hidden, shown, or resized in the program)
AdjustmentListener
Listens for adjustments (like a scroll bar being engaged)
How to code a listener to a button?
button.addActionListener(new ActionListener()) { }
If you wanted to know if a user selected ‘‘Oranges’’ from a list of check boxes, which event listener is most appropriate?
The ItemListener helps you identify if a given item (such as a check box) has triggered an event.
How to use the ActionListener interface?
addActionListener()
How many options can the user select out of a JCheckBox?
As many items as they want
What GUI class serves as a foundation on which to add elements?
JFrame
Consider the following Java code. What is the name of the constructor for the class being instantiated?
JFrame thisFrame = new JFrame(‘Hi There’);
JFrame()
Constructors share the name of the class. Therefore the constructor for JFrame is JFrame(), and it accepts a parameter; in this case we are sending text.
The Graphics2D class is an extension of what other Java class?
Graphics
How to create a rectangle using the Graphics2D instance named g3?
g3.draw(new Rectangle2D.Double(20, 100, 100, 50));
What is the Java classes is used to create and render 2-dimensional graphics?
Graphics2D class is used to render 2-dimensional shapes, text and images, as well as provide color management, and text layout in Java GUI applications.
Which place is the best to look for all the methods available in the Graphics2D class?
Javadocs