Java Basics Flashcards

Writing your first Java program The different parts of a Java program Printing text to the console Organizing your code using methods How Java views and stores basic types of data Different methods of manipulating data How to create programs that allow a user to interact with the software

1
Q

What are some key features of Java?

A
  • Object Oriented
  • Compiled
  • Memory management
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a compiler?

A

The part of Java that translates your source code into machine code

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

What are the steps in creating a new .java file in your “IDE” (Integrated Development Environment)?

A
  1. Project Name - This is what you enter when you are creating a new project with the IDE dialog boxes. This will be the name of the folder where all your different project files will be kept. For example, you might call your project “Java practice” and put all your different code files in one project.
  2. Java File Name - this is the name of the actual file that will hold your code. It will be stored in the source or “src” folder within your IDE project. This should follow the below java naming conventions.
  3. Class Name - this is the name of the class that you declare in your code. Java requires that this name exactly match the name of the .java file. In fact, the IDE will automatically name your class for you based on what you entered for the file name.
  • Java Naming Conventions As you create new Java files and Classes you must give each a unique name. Java has its own “conventions” or suggested formats for how to create these names: No spaces Must start with a letter Capitalize the first letter of each new word i.e. HelloWorld
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are “Key Words” in Java?

A

You’ll know if you’ve written code correctly because certain words should change colors within your IDE. These are called “key words” and your IDE should highlight them to make it easier for you to read your code.

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

What is a class?

A

The class is the outermost layer of the program. It starts with the keywords “public class” and then whatever the name of your file is.

public class YourClass {

The name of your class has to exactly match the name of your file, including capitalization. The class is enclosed by a set of curly braces or “{ }” characters. All code you want to run should be placed between these two characters.

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

What is the main method?

A

The main method is the wrapper that tells your computer which lines of code to run. In Java it has a very specific series of keywords:

public static void main(String[] args) {

After the open curly brace, you should put each line of code you want the computer to run. Don’t forget to add the closing curly brace after all your code. As you can see in the image it is convention to add a layer of indentation between the main method and the class, this shows that the main method is inside the class.

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

What is a statement?

A

The statements are the lines of code for the computer to run. Each line is called a “statement” and should end with a semi-colon(;). You can have as many statements as you want, the computer will run each line from top to bottom one after the other. Again, as these are inside the main method all statements should be one level of indentation in.

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

What happens if you forget to add a semi-colon at the end of a line of code?

A

The computer reports a “compiler error”

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

What are comments?

A

Comments are notes written in the source code by the programmer to describe or clarify the code. They are ignored by the Java compiler so they are intended only as messages to the humans that will read the code files.

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

When is it recommended to add comments?

A

It is recommended that you add comments…

  • At the top of any Java class to describe its overall function
  • At the top of a “method” or a small subsection of code to help explain its contribution to the overall solution
  • To explain what is happening when you have particularly complicated bits of code
  • To isolate lines of code when looking for issues without having to delete code

There are two different ways to add comments:

Single line comments

// comment text, on one line

Multi line comments

/* comment text You can have as many lines as you like Between these two indicators */

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

What is a string?

A

In Java, a String is any sequence of characters – letters, digits, spaces, punctuation, and other “special characters”. Here are some examples of Strings defined in Java:

“Hello, world”: This string has 12 characters. The space between the comma and “w” is also counted as a character. The double quotes are not part of the String, they define where the String starts and where it ends.

“12234”: This is a String, not an integer number because it’s enclosed in double quotes.

”><}{_^$#@^”: This is a String with 10 special characters in it.

””: This is a special String: an “empty String” that contains NO characters at all. The two double quotes are right next to each other, without even a space between them.

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

What is an escape sequence?

A

What if you want to create a String that contains a double quote character? Tricky! If you wrote “””, Java would be confused. The computer can’t tell if “”” is an empty String followed by a double quote, or a String consisting of a double quote character. Java includes a way for you to clarify this ambiguity with what is called an “escape sequence”. When Java sees a backslash in a String this tells Java to “escape” or skip the next character’s function and simply add it to the String:

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

What are Printlns?

A

To produce String based output we use the println statement. This is a type of computer “output”. The place you look on your screen for text output from a Java program is called the “console”

Java prints text out to the console using a System.out.println statement. Here’s the one you used in your HelloWorld program:

System.out.println(“Hello, world!”);

It’s kind of wordy, but the words do make sense in a way:

  • System essentially refers to the computer as a whole
  • out refers to the standard output device: the console
  • println indicates that you want to “print” as a complete line (ln) of text

Our statement above will print Hello, world! to the console area on your screen. It also advances to the next line on the display, just as if you typed it and then hit the Enter (or Return) key.

You can also use the println statement to produce an empty line.

System.out.println();

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

What are Prints?

A

Sometimes you may want to use several print statements and have all the output produced on the same line. For this, you can write print instead of println. For example, these statements:

System.out.print(“Hello, “);

System.out.print(“Joe”);

System.out.print(“! Hello, “);

System.out.print(“Jane”);

System.out.println(“!”);

…would print out:

Hello, Joe! Hello, Jane!

… and advance to a new line only after the last exclamation point. That is because you can see that the first 4 calls leave off the “ln” at the end of print. These are simply “prints” instead of “print lines” and do not add the carriage return or “Enter” at the end of a line of output.

Finally, you can also print multiple lines with a single println statement by using the new line escape sequence from above:

System.out.println(“line 1\nline 2\nline3”);

… prints out these three lines:

line 1

line 2

line 3

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

What is procedural decomposition?

A

The process of breaking a task down into smaller parts is called “procedural decomposition”, and almost all programming languages provide a way to do this. Java does it using what it calls “methods”. In general, you should break your program up into methods when:

  • You can break a task into distinct non-trivial subtasks in order to understand it better. For example:

Fly airplane

  1. Take off
  2. Fly
  3. Land

You could even break one or more subtasks down further:

Fly airplane

  1. Take-off
  2. Push back from gate
  3. Taxi to runway
  4. Increase speed until off ground
  5. Climb to cruise altitude
  6. Fly
  7. Land
  • You have “redundant code”: unnecessarily repeated code that appears more than once in your program. It’s OK to use methods to eliminate redundancy for even a single, complicated line. That way if you ever have to change it, you only have to change it in one place!
  • Your method is getting bigger than 20-30 lines of code; look for groups of statements that are related pull them out into a method.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the ideal relationship between a main method and methods?

A

Ideally, once you have organized your program with methods, your main method turns into a list of method calls, each that handle their own small piece of the task to be performed. Thus your main method turns into a sort of outline of what your code is doing, making it easier for someone reading your code to quickly understand what it does.

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

What is “camel case”?

A

The Java convention is for method names to start with a lower case letter, and use uppercase letters to start each following word with no spaces. This is called “camel case”: the uppercase letters are the camel’s humps! Here’s how the methods for our flying example should look:

flyAirplane

takeOff

pushBackFromGate

taxiToRunway

increaseSpeedUntilOffGround

climbToCruiseAltitude

As the purpose of a method is typically to accomplish a task, it’s a good idea to start a method’s name with a verb: calculate, report, print etc… Followed by whatever item that task is performed on: calculateAge, reportResults, printSummary etc…

18
Q

How do you write a method?

A

The first line of a method is called the “method header” and it contains some specific keywords:

public static void myMethod() {

Each of these keywords have specific functions, and we’ll learn about some of the other keywords later in this course. For now, we’re going to keep it simple so all our methods will be public, static, and void. Here is the syntax for creating your own method including the method header:

public static void methodName () {

statement 1

statement 2

statement n

}

This is called “defining” a method, and you should place your methods after the main method. This means they should be placed after main’s closing curly brace, but before your class’s closing curly brace.

You would use your method name in place of methodName, and enclose all the statements of your method inside curly braces { }.

19
Q

What is a method call?

A

To actually run the code inside your method, another method has to “call”, or invoke, it by name. Each method invocation statement starts with the name of the method you want to execute, followed by a pair of parentheses finishing with a semicolon. Again using our flying example, here’s how the method calls would look:

public static void main(String[] args) {

takeOff();

fly();

land();

}

public static void takeOff () {

pushBackFromGate();

taxiToRunway();

increaseSpeedUntilOffGround();

climbToCruiseAltitude();

}

When you call a method, the computer jumps to that method definition, runs all the code inside that method, then returns to the line where it was called.

20
Q

What is “control flow”?

A

Here are the rules computers use to run your code we’ve encountered so far:

  1. First, find the main method. If your program doesn’t have a main method to get it started, it won’t run!
  2. Execute each statement in the main method from top to bottom, starting with the one right after the opening curly brace.
  3. If the statement is a method call, jump to that method definition and execute each of the statements in that method from top to bottom.
  4. When you reach the end of a method (represented by its closing curly brace), “return” to where you encountered the method call and continue with the next statement following the method call.
  5. When you reach the end of the main method, end execution and close the program.

These rules control the “flow” of our program from one statement to the next, this is called the “control flow” of the program.

21
Q

What is an integer?

A

Integers represent whole numbers. You may be familiar with integers from algebra class. Integers are numbers that are not fractions nor have decimals, for example, 422, -13 and 0. Java refers to these as type int.

22
Q

What is a double?

A

Doubles are real numbers like 3.14159, -2.718, and 2145.2731. You can also write these in a form of scientific notation; for example, 1.23e2 is the same as 123, and 921e-1 is 92.1. For historical reasons, Java calls these type double.

23
Q

What is a character?

A

Characters are single characters such as letters, symbols and spaces. These are not just limited to english, but all languages. For example, A, X, 0, z, ?, and =, but also Ω, ä, Я, and many more! Each of these is a char in Java. When you define a char, enclose it in single quotes, like ‘a’. String objects are made up of char characters. NOTE: ‘a’ is NOT the same as “a”: the first is a char, the second is a String that contains a single char.

24
Q

What is a Boolean?

A

Booleans are a type of data that can only have either two values: True or False. Booleans are the building block for logic based decisions, you can think of them as representing yes or no, on or off, positive or negative, etc… Java calls these boolean values

25
Q

What is a variable?

A

All of the data we’ve seen so far have been literals of various types: specific fixed values, like 13 or 1.3 or “abc”. Most useful programs also need to use data whose values change, for example, like a count of points scored in a game, or the amount of time remaining. In Java there is a construct to hold data who’s value changes, these are called variables. You can think of a variable as a named box (or cell) in memory that holds a value that the program can use or change and refer to by name.

This is similar to using variables instead of numbers in algebra – an algebra equation uses a variable to define what to do with any value the variable can contain. For example, the equation of the line y = x + 2 says that whatever the value of x is, y is 2 more than x. Thus x is a stand-in for a range of possible numbers.

26
Q

Why and how do you need to declare a variable in Java before you use it?

A

Before we can use a variable in Java, we must “declare” it. To do this you must tell Java what type of data you want your variable to store and give the variable a unique name within the given scope.

dataType variableName;

For example, to declare a variable of type String with the name “myString” we write:

String myString;

You can only declare a variable once. If you try to declare it a second time, Java will report it as an error. This also means you can only use the name of a variable once within a single scope.

27
Q

How do you assign a value to a variable?

A

Declaring the variable creates the space in memory for a value, to actually store a value in that space you use an “assignment statement”. An assignment statement associates the given value to the named variable. The assignment statement starts with the name of the variable whose value we are setting, then an equals sign, then the value we want to set, and finally, a semicolon to mark the end of the statement:

variableName = value;

If we wanted to store the String “Hello, world!” in our variable from before

myString = “Hello, world!”;

We can now use the variable anywhere we could have used the literal string. This statement would now print “Hello, world!” to the console:

System.out.println(myString);

If we set the variable to a new value and then repeat the same println statement, it will print out the new value “Hello yourself!” instead:

myString = “Hello yourself!”;

System.out.println(myString);

Java allows you to assign an initial value to a variable when you declare it; this code combines the first two statements above:

String myString = “Hello, world!”;

System.out.println(myString);

myString = “Hello yourself!”;

System.out.println(myString);

Output:

Hello, world!

Hello yourself!

28
Q

What is meant by “local variable”?

A

Any variable you declare between the curly braces of a method is called a local variable because you can only use it locally inside the method. If you try to use it outside the method, Java will report an error, “cannot find symbol”. In general, we say that a variable’s scope is the lines of code where it can be used, the places in your code where it is “visible”.

You can, however, declare two different variables that use the same name in two different methods! Consider this code:

public class Song {

public static void main (String[] args) {

String line = “This is the chorus”;

System.out.println(line);

verse();

System.out.println(line);

}

public static void verse() {

String line = “This is my verse”;

System.out.println(line);

}

}

This program has two variables named “line”, but one is local to the verse method and can only be used there, and the other is local to the main method, and can only be used there. So, the program prints:

chorus

verse

chorus

29
Q

What is a class constant?

A

In addition to declaring local variables inside a method, you can also declare variables that are NOT part of any method, but whose scope is the entire class – these are called, not surprisingly, class variables. For now, we will use these only for declaring variables whose value never changes – called “class constants”.

To declare one of these, you need to add the terms public static final before the type, AND set the value as you would in an assignment statement. It’s best to place these right below the class declaration like this:

public class myClass {

public static final double PI = 3.14;

public static final int MAX_SPEED = 80;

public static final int DAYS_IN_WEEK = 7;

public static void main(String[] args) {

Note that the Java naming convention is to use all capital letters for class constants, separating words by underscores to make them readable – because remember no variable names can have spaces in them!

30
Q

Why is it a good idea to use class constants?

A

Why declare a variable with a fixed value? Isn’t the whole point of a variable is that its value can vary? Well, yes, but there are two common and useful ways to use a class constant:

  1. You want all methods in the class to use exactly the same value for something; for example, use 3.14 for PI, or MAX_SPEED for 80. If you later want to change this value, you only have to change it in one place. This not only avoids having to find everywhere it’s used and change it multiple times, but, more important, ensures that you don’t overlook one place or accidentally change an 80 somewhere in the program that represented a maximum age instead of a speed!
  2. You want to use names rather than values so that the meaning of an expression is clear; for example, using DAYS_IN_WEEK instead of 7 as in:

calendarRows = DAYS_IN_WEEK;

It is considered good style to replace repeated numbers with a class constant whenever possible to make your code more readable.

31
Q

How are arithmetic expressions similar in Java and Algebra?

A

You can write arithmetic expressions in Java just like you do in algebra. Addition(+), subtraction (-), multiplication (*) and division(/) all work for both int and real data types. You can use parentheses as well to force an evaluation to have a higher level or precedence. The order of operations is left to right, and the precedence is also the same as in algebra:

  1. Parentheses
  2. Multiply and Divide
  3. Add and Subtract

Many algebra teachers summarize this as PEMDAS, but in Java, it’s really PMDAS because there is no exponent operator.

Dividing two integers in Java can be a little confusing: 7 / 2 gives a result of 3, not 3.5! That’s because when Java divides two integers, it drops (or “truncates”) the decimal part to make the result an integer too. It does not round!

Java does provide another operator for getting the remainder: %, generally called “mod”, short for modulus. For example:

7 % 2 == 1

15 % 4 == 3

6 % 2 == 0

32
Q

What are some Java math “shortcuts”?

A

Java provides some extra arithmetic operators for things that programs do frequently. They don’t do anything you can’t do with the simple +, -, *, / and % operators; they’re just quicker to write, and, once you’re fluent in Java, easier to read at a glance. These operators work with both integers and doubles:

33
Q

How does Java calculate mixed int and double expressions?

A

Whenever Java applies an operator to two int values or variables, the result is also of type int; when it’s two doubles, the result is always a double. But, if you use an operator with one int and one double, the result is always a double, and it doesn’t matter which comes first. This makes sense since every int can be represented as a double, but certainly not vice versa! So, all of these evaluate to 1.5:

3.0 / 2 == 1.5

3 / 2.0 == 1.5

3.0 / 2.0 == 1.5

And, all of these evaluate to 2.0 (a double), not 2 (an int):

3.0 - 1 == 2.0

3 - 1.0 == 2.0

3.0 - 1.0 == 2.0

This seems very simple, but when you combine it with the order of operations, it can become confusing. For example,

7 / 2 * 2.0 == 6.0

BUT

2.0 * 7 / 2 == 7.0

In the first, Java divides the two integers 7/2 and gets the integer 3, and then multiplies the integer by the double 2.0 to get a double 6.0. In the second, it multiplies the double 2.0 by 7 and gets the double 14.0, and then divides that double by the integer 2 and gets the double 7.0. The order in which you write an expression matters a lot when using a combination of integers and doubles!

Here are some examples of how the computer would evaluate some expressions that combine types, step by step:

34
Q

What is String Concatenation?

A

One of the arithmetic operators can also be used on Strings: the plus sign (“+”). When used with two Strings, it simply “concatenates” (connects) the two to make a single new String with all the characters of the first, followed by all the characters in the second. For example,

35
Q

What happens when you concatenate a String, including an empty String, with any other data type?

A

Java returns a string:

36
Q

How does Java handle combining mathematical operations and Strings?

A

Java will evaluate the expression from left to right, converting between types as appropriate. So the following expression:

1 + 2 + “3” + 4 + 5

… results in:

“3345”

However, the order of operations applies when combining mathematical operations and concatenation, like so:

1 * 2 + “3” + 4 * 5 = “2320”

If you’re concatenating two words or similar values you may need to add a String with a space character between them:

String firstName = “John”;

String lastName = “Doe”;

System.out.println(var1 + var2);

System.out.println(var1 + “ “ + var2);

… results in:

JohnDoe

John Doe

37
Q

What is “Casting”?

A

As the last two sections showed, you need to be careful when combining values of different data types. Java lets you explicitly change data from type to another or “cast” the data to a different type. You do this by expressly calling out what you want your data type to be after evaluation:

(resulting data type) expression;

Casting has higher precedence than any other operator (except parentheses, of course), and only cast the value immediately to its right.

The most common use is to cast a double into an integer for rounding the result of an integer by integer division instead of truncating it:

38
Q

What is a “Scanner”?

A

it is an object designed to handle text input. It is not built in, so we need to tell Java to look for it in the util library with this special line at the beginning of our program:

import java.util.*;

Then, typically in a method, we create our own Scanner object with a name we define, like “input” and tell it to read text from System.in (the equivalent of the System.out we use for output):

Scanner input = new Scanner(System.in);

Finally, we tell our object to get the next complete line of input from the user into a String variable:

String name = input.nextLine();

39
Q

What is the syntax for Scanner?

A

import java.util.Scanner;

public class LearnScanner {

public static void main(String[] args) {

Scanner input = new Scanner(System.in); System.out.println(“Welcome!”);

System.out.print(“What is your name?”);

String name = input.next();

System.out.println(“Hello “ + name);

}

}

The above code creates a new scanner and allows the user to type in any String. When Java gets to the line “input.next()” it pauses and waits for the user to type something into the console and hit “enter”, then it picks back up where it left off. In this case you can type in any String without white space and it will be stored in the variable “name”.

40
Q

What if you want the user to input an int or a double?

A

What if you want to get an int or a double instead of a String? Easy:

int count = input.nextInt();

double amount = input.nextDouble();

These allow the user to enter in numbers that you then save in the appropriate data types. Maybe you want to get some more information about your user you could read in multiple items like this:

String name = input.next();

int age = input.nextInt();

double weight = input.nextDouble();

System.out.println(name + “ is “ + age + “ year old and weighs “ + weight + “kg”);

The one drawback to this simple use of a Scanner is that if you expect the user to enter and integer, and then enter something else, the program will immediately end with a cryptic error message like:

Exception in thread “main” java.util.InputMismatchException

The same problem happens with a double, although the scanner will happily accept an integer input and convert it to a double just like it does in an assignment statement. There are ways of dealing with this cleanly, but we’re going to trust the user to enter the right things for now!

You can also let the user enter in as much as they like, including spaced by using the nextLine method. This will return a String of everything the user types before they hit “enter”.

String line = input.nextLine();