General Flashcards

1
Q

Java is platform independent

A

Programs written in Java can be executed on any operating system (Windows, Linux, Mac, etc.)

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

Bytecode

A

Java compiles source code into bytecode. Bytecode is platform independent. There is no difference between bytecode for Windows, Mac, or Linux. The JVM converts bytecode into machine code for the specific platform that the user uses.

Advantage of this two-step compilation is that Java can be run on all platforms that have the JVM installed.

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

JDK, JRE, JVM

A

JDK includes JRE, which contains the JVM

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

Integrated Development Environment (IDE)

A

IDE contains text editor and GUI to debug, compile, and run programs.

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

Package

A

A grouping of related classes and interfaces. Two or more files can have the same name if they belong to different packages.

Java has many pre-created packages, such as java.io (input/output) and java.awt (code for implementing GUI). To use pre-written packages, you need to import them.

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

main() method

A

Whenever a Java application is started, the main() method is the first method to be called. main() takes an array of string as input.

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

Statement

A

Every statement ends with a semicolon

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

Declaration

A

Example: int age;

Your program allocates memory to store this data.

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

Primitive data types

A

8 primitive data types.

4 of them are for integers:

  • byte: Integers -128 to 127. Byte of storage.
  • short: 2 bytes storage. -32768 to 32767
  • int: 4 bytes storage. -2^31 to (2^31) - 1.
  • long: 8 bytes. -2^63 to (2^63) - 1. Rarely used.

2 of them for floating point numbers (numbers with fractional parts):

  • float: 4 bytes storage. -3.40282347 x 10^38 to 3.40282347 x 10^38. Precision of 7 digits. This means if you use float to store a number like 1.23456789 (10 digits), it will be rounded to 1.234568.
  • double: 8 bytes storage. Range of -1.79769313486231570 x 10^308 to 1.79769313486231570 x 10^308. Precision of 15 digits.

By default, floating point in Java is double.

Two more primitive date types:

  • char: stores single Unicode character. 2 bytes memory. When you initialize a char you need to put the character in single quotes.
  • boolean: can only hold 2 values: true and false.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Naming a variable

A

First character cannot be number. Reserved words cannot be used. Examples of reserved words are System, if, While, etc.

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

Initialization

A

Giving a variable a value. You can initialize at deceleration or in a separate statement. You can initialize severance variables on the same line (you separate them by a comma).

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

Basic operators

A

+, -, *, /, %

x = 7, y =2
x / y = 3 (rounds down to nearest integer)
x % y = 1 (gives remainder)

If either x or y is a floating point number, the result will be a floating point number.

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

++ and - - operators

A

System.out.println(counter++); will first print counter and then increment it.

System.out.println(++counter); will first increment counter and then print it.

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

Casting

A

Do not need to explicitly cast when converting smaller data to large data. (I.g., int to double).

When casting larger data to smaller data, need to explicitly cast.

Example: int x = (int) 20.9.
x = 20.

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

String

A

String is a reference data type (not primitive data type). This means it’s an object. Specifically, an object of the String class.

To assign a String variable, you must enclose the text in double quotes.

“+” operator can concatenate two strings.

Java String class has methods.

Whenever you use a method, you need to use the dot operator.

Common ones:

  • length(): total number of characters the string has (whitespace included)
  • toUpperCase()/toLowerCase(): converts string to upper/lower case.

Example: String uCase “Hello World”.toUpperCase(); uCase = “HELLO WORLD”.

  • substring(6): returns a substring starting from index 6 until the end. Indexing in Java starts at 0, not 1.
  • substring(1, 8): same as above, but extracts from index 1 to 7. Stops AT index 8, NOT AFTER. Thus letter at index 8 is NOT included.
  • charAt(1): returns character at index 1.
  • equals(): returns true if two strings are identical. Example: boolean equalsOrNot = “This is Jamie”.equals(“This is Jamie”);
  • split(): splits a string into substrings based on a user-defined separator (also known as delimiter). Returns an array that contains resulting substrings.

Example: String names = “Peter, John,” Andy, David”;
String[] splitNames = names.split(“, “); Delimiter is comma followed by space.

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

Array

A

Collection of data that are normally related to each other.

Can be declared int[] userAge or int userAge[]. Latter syntax is not proffered.

3 ways to declare and initialize array:

1) int[] userAge = new int[] {21, 22, 23, 24, 25};

Can be simplified to:

2) int[] userAge = {21, 22, 23, 24, 25};
3) int[] userAge = new int[5]; Default values are 0. We then have to initialize.

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

Array methods (Arrays class)

A

Arrays come with pre-written methods. They’re found in java.until.Arrays class. To use them, you have to add the statement import java.until.Arrays; to your program. This tells the compiler where to find the code for these methods. Import statement must appear after package statement and before class declaration.

We don’t need an import statement to use String methods since the String class is present in the java.lang package which is imported by default.

Commonly used methods:

  • equals(). Returns true if two arrays are equal. (I.g,: boolean result = Arrays.equals(arr1, arr2);

All methods in Arrays are static. Hence we had to add “Arrays” in front of the method name.

  • copyOfRange(): 3 arguments. Copy the contents of one array into another. Example: int[] dest = Arrays.copyOfRange(source, 3, 7); Copies elements from 3 to 6 (NOT 7).
  • toString(): 1 argument. Returns a String representation of array contents.
  • sort(): sorts array in ascending order. Does not return new array. It modifies existing array.
  • binarySearch(): 2 arguments. Allows you to search for specific value in SORTED array. Make sure array is sorted first.

Example: int foundIndex = Arrays.binarySearch(myInt, 78); Returns index of 78 if it exists in array myInt. If the number is not found, it will return a negative number. Negative means it’s it’s not found, and the number tells you which POSITION (NOT INDEX) should be if it were to exist in the array (I.g,: -4 means position 4, index 3).

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

Fields vs methods

A

Come back

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

Array length

A

No length() method. Instead, we use field length.

userAge.length; (no “()” )

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

Primitive Type vs. Reference Type

A

All data types in Java fall into one of two categories: Primitive Type or Reference Type. There are only 8 primitive types. The rest are reference types.

Reference types include Strings, arrays, classes, and interfaces.

One of the main differences between the two is how data is stored.

Primitive type stores its own data. With int myNumber = 5; the variable “myNumber” stored the actual value 5.

Reference type does not store the actual data. Instead, it stores a reference to the data. It does not tell the compiler what the value of the data is; it tells the compiler where to find the actual data.

For example, with String message = “Hello”; the variable message does not store the string “hello”. Instead, message stores the address of the memory location of “hello”.

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

Strings are immutable

A

Immutable means the value cannot be changed. When we update a Strong variable, we are actually creating a new string and assigning the memory address to the String variable.

Example:

String message = “hello”;

update message:

message = “World”;

The compiler does not go to the storage location where “Hello” is stored and change the value to “World.” Instead, it creates a new string “World” and stores it somewhere else in memory. This new address is then assigned to the variable message. In other words, there are TWO string now: “Hello” and “World”. If “Hello” is no longer needed, it is destroyed to free up memory. This is called garbage collection, which Java handles automatically.

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

System.out.println();

A

PrintStream class tbc

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

Escape sequences

A

Sometimes we need to print special “unprintable” characters, such as a tab or a newline. You need to use the \ (backsplash) character to escape characters that would otherwise have a different meaning.

Example:

System.out.println(“Hello\tWorld”);

Output:

Hello World

Commonly used escape sequences:

Printing a newline: \n.
Example:
System.out.println(“Hello\nWorld”);

Output:

Hello
World

Print the backslash character itself:
Example: System.out.println(\);

To print double quotes so that the double quotes don’t end the string: \”
Example: System.out.println(“I am 5’9\” tall”);

Output:

I am 5’9” tall

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

Formatting outputs: printf()

A

printf() is more complex than println(), but it offers more control.

printf() requires more than one argument. The first argument is the string to be formatted. The other arguments replace the format specifiers (%.3f, %d, etc.) which serve as placeholders.

Format specifiers always begin with a percent sign % and end with a converter (such as f or d). In between % and converter, you can add flags. For example, in %.3f, “.3” is a flag. It indicates that we want to display the number with 3 decimal places.

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

Converters

A

Integer converter: d.
Works for integers such as byte, short, int, and long.

Floating point converter: f. Works for float and double.

Newline converter: n. Moves cursor to next line.

26
Q

Flags

A

Width flag: total width of output.

Example: System.out.printf(“%8d”, 12);

Output:
12

System.out.printf(“%8.2d”, 12.4);

Output:
12.40

Thousands separator flag: ,

Example: System.out.printf(“%,d”, 12345);

Output:
12,345

System.out.printf(“%,.2f”, 12345.56789);

Output:
12,345.57

27
Q

Accepting input from user

A

Easiest and most common way is to use Scanner object. Import Scanner class using import java.until.Scanner;

Create a scanner object and pass System.in as an argument

System.in tells the compiler that you want to get input from the standard input device, normally a keyboard.

Scanner reader = new Scanner(System.in);

Scanner has methods we can use to read input from the user.

Most commonly used methods:

-nextInt();
-nextDouble();
-nextLine();
for reading int, double, and String stats types respectively. They return those values.

If you type the wrong data type, the methods will try to convert them. If that fails, you’ll get an error.

28
Q

Ternary operator: 3 > 2 ? 10 : 5;

A

If condition (3 > 2 in this case) is true then return 10. Else return 5.

Example:
int num = 3 > 2 ? 10 : 5;

num is equal to 10.

29
Q

Enhanced For Statement

A

Can be used when working with Arrays and Collections.

Syntax:

for(variable declaration : name of array)
{

}

30
Q

Do-while Statement

A

do-while is similar to while statement with one main difference—the code within the curly braces of a do-while statement is executed at least once.

Example:

int counter = 100;

do {
System.out.println(counter);
} while (counter < 0);

Counter 100 will print ONCE.

31
Q

Branching: break vs. continue

A

Break exists the loop permanently. Continue skips everything written below it and goes to the next iteration.

32
Q

Exception handling

A

Tbc

33
Q

Object Oriented Programming

A

OOP is an approach to programming that breaks a programming problem into objects that interact with each other.

Objects are created from templates known as classes. Class can be thought of as a blueprint of a building; an object is the actual building that we build based on the blueprint.

Writing our own class:

accessModofier class ClassName {

}

Example:

public class Car {

}

Access modifiers are like gate keepers. They control who had access to that class. In other words, they control whether other classes can use a particular field or method in that class.

Public means it can be accessed by any class in the program. Package-Private means it’s only accessible to other classes within the same package. There can be more than one package within a single Java application.

If you do not write an access modifier, it is package-private by default.

Convention is to use PascalCasing when naming a class (first letter of EVERY word is capitalized).

Contents of class are enclosed in curly braces. Contents include constructors, fields, methods, interfaces, and other classes.

There can only be one public class per Java file and that public class must have the same name as the file. The main() method is inside this public class.

34
Q

Fields

A

Fields are variables declared at top. Can be declared public, private, or protected. Package-Private by default.

Private means it can only be accessed within its own class (different than package-private).

This is encapsulation—hiding data and behavior from other classes that don’t need to know about them. This makes it easier to change code in the future.

Final keyword means that the value cannot be changed after it is created. A final variable must be initialized at deceleration or within constructor.

35
Q

Methods

A

A method can access all fields declared in the class. It can also declare local variables. These are only accessible within the method.

Can be more than one return statement, but once it encounters the first one it’ll exit the method.

Sometimes a method does not need to return an answer but simply uses the return statement to exit the method.

36
Q

Overloading

A

Two methods in the same class with the same name. They need different signatures. Signature is the name of the method and the parameters.

37
Q

Getter and Setter Methods

A

Fields declared private cannot be accessed outside the class. If they’re needed by another class, we use getter and setter methods.

Why do we allow this if it seeks to contradict encapsulation? Because it gives us greater control over the rights other classes have when accessing private fields. For example, we can use if-statements in setter method to control what the private field can be set to.

Convention is to name setter methods startling with “set” and getter methods starting with “get”.

38
Q

Constructors

A

Constructors are a block of a code similar to a method that construct and object from a the class template. It’s always the same name as the class, and is commonly used to initialize fields in the class.

Constructor is the first block of code that is called when we create an object from the class.

A constructor does NOT have a return value and we do NOT have to use the void keyword.

A class can have more than one constructor as long as the signature is different.

Declaring a constructor is optional. If we don’t declare one, a default constructor will automatically be generated. Default constructor does not have any parameters, and it initializes fields to their default values. (0 for numeric type and null for reference type.)

39
Q

Dot operator for objects

A

Only needed when accessing members of a class from a different class. Not needed in same class.

40
Q

Static keyword

A

If you want to call methods are access fields of a class without creating an object, you use the static keyword in that class for that object or field.

To access non-static methods you need to create an object of the class. Not so for static members. We just use the class name to access them.

41
Q

Pass by value

A

Java is pass by value. But when you pass a reference type variable, a copy of its address is provided. Hence changing it in the method will change the argument value.

For primitive type values you pass a copy of the value and not the address. Hence changing it in the method had no effect on the the argument.

42
Q

Inheritance

A

Key concept of OOP. Inheritance allows us to create a new class from an existing class so that we can effectively reuse existing code. All classes in Java are inherited from a pre-written base class known as the Object class.

Object class has pre-written methods, such as toString(), that we can use whenever we work with classes.

43
Q

Parent class, base class, or superclass. Child class or subclass.

A

For a class to inherit a class, you write “extends ParentClassName” after the name of the child class.

One exception is inheriting Object class. We don’t need to use the keyword “extends”.

A child class inherits all PUBLIC and PROTECTED fields and methods from the parent class. This means we can use those methods and fields without coding them in the child class.

Child class does NOT inherit private fields and methods of the parent class. Thus it cannot access these methods directly.

When we write the child class constructor, the parent class constructor is called first. By default it calls the parameterless constructor. If we want it call a non-parameterless constructor in the parent class, you have to use the “super” keyword.

Example:

public NormalMember (String pName, int pMemberID, int pMemberSince)
{
super (pName, pMemberID, pMemberSince);

System.out.println(“Child Constructor with 3 parameters”) ;
}

Super must be the first statement in the constructor.

Private fields are NOT inherited, which means the child cannot access them directly. However, these fields DO exist in child class. It just must use constructors or setter or and getter to access them.

You can assign members of child class to parent class type. For example, an array of members can be set to both NormalMember and VIPMember if NormalMember and VIPMember are child classes of member. You can also assign Member (parent type) to it.

44
Q

Overriding

A

Overriding a method simply means writing a new version of the method in the child class.

45
Q

Annotations

A

Example: @Override. Annotations are metadata that provide the compiler with extra info.

46
Q

Polymorphism

A

Closely related to inheritance. Polymorphism refers to a program’s ability to use the correct method for an object based on its run-time type.

Example:

47
Q

Abstract classes

A

An abstract class is a special type of class that is created purely to be a base class for other classes to derive from. They cannot be instantiated.

In other words, if FourWheelVehicles is an abstract class, the statement

FourWheelVehicle myVeh = new FourWheelVehicle();

will give you an error as you cannot create an object of an abstract class.

Abstract classes may have fields and methods just like any other class. In addition, they can have a special type of method known as abstract methods. Abstract methods are methods that have NO BODY and MUST be implemented in the DERIVED class.

The keyword abstract is written as the first word of the class declaration. It is also written before “public/private” of a method that is meant to be abstract. Additionally, braces are not added after the method declaration, since it has no body. We end the deceleration with a semicolon instead.

48
Q

Interfaces

A

Interfaces are like abstract classes in that they cannot be instantiated. Instead, they must be implemented by classes or extended by other interfaces.

When a class implements an interface, it had to implement all the abstract methods in that interface.

One key difference between an abstract class and an interface is that a class can only extend one abstract class but can implement multiple interfaces.

Another difference is that an interface can only contain abstract methods (up until Java 7), while an abstract class can contain non-abstract methods.

You don’t need to write abstract in an interface. It is abstract by default.

You use “implements” for interface, not “extends.”

In Java 8, interfaces can have default and static methods.

49
Q

Access modifiers

A

4 total:

  • private
  • public
  • protected
  • package private by default
In short, anything that is declared as public is accessible everywhere;
there are no restrictions on accessing public fields. On the other hand,
anything declared as private is only accessible within the class in which
it is declared. Anything declared as protected is accessible within the
class in which it is declared, any class that is derived from it and any
class that is in the same package as the class that it is declared in. Finally,
anything declared without an access modifier is package-private and is
only accessible within the package in which it is declared.

Public is accessible anywhere. Package-private only same package. Protected in inherited classes and package. Private only in the class it was declared.

50
Q

Collections

A

The Java Collections Framework is a set of pre-written classes and interfaces that Java provides to help organize and manipulate groups of data.

51
Q

Autoboxing and Unboxing

A

Because Java is an object oriented, primitive types need to sometimes be converted to Objects. Java provides wrapper classes for this. Each primitive type has a corresponding wrapper class.

Wrapper classes are:

  • Boolean
  • Character
  • Byte
  • Short
  • Integer
  • Long
  • Float
  • Double

Converting is easy.

From int to Integer: 
Integer intObject = new Integer(100); 

From Integer to int:
int m = intObject.intValue();

Autoboxing enables automatic conversion.

We can just do
Integer intObject = 100;

Likewise, unboxing converts from Integer to int as follows:
int m = intObject;

52
Q

Wrapper classes

A

Wrapper classes also have a major use of providing methods for converting strings into primitive types.

For example, you can convert a string to an int using Integer.parseInt();

If the string (like “ABC”) cannot be converted, the method will throw a NumberFormatException.

Can also convert string to double.

53
Q

Lists

A

Very similar to array, but more flexible. Most importantly, it’s size can be changed.

List is an interface that is part of Collections Framework.

They most common classes that implement list are ArrayList and LinkedList.

54
Q

ArrayList

A

Implements List interface. Like all collections, can only store objects, not primitive types. Thus, you must use wrapper classes for primitive types.

Syntax for declaration:

ArrayList al = new ArrayList<>();

You could instead declare it using List:

List al = new ArrayList<>();

This is allowed because List is superinterface of ArrayList.

Methods:

Can be used declared ArrayList or declared List and assigned an ArrayList to it.

  • add(); or
  • add(index, value);
    To add members to list.
  • set(index, value);
    To change value.
  • remove(index);
    To remove value.
  • get(index);
    To get element.
  • size();
    Number of elements in List.
  • contains(value);
    To check if List contains value.
  • indexOf(value);
    Index of first occurrence of value.
    Returns -1 if value doesn’t exist.
  • toArray();
    Returns array of objects (object superclass).
    Cab also specify to return Integer array and the like with Integer[] arr = xyz.toArray(new Integer[0]);
  • clear();
    Te remove all elements in the list.
55
Q

LinkedList

A

Very similar to ArrayList. Both implement List interface. Main difference is implementation. ArrayList uses resizing array. LinkedList uses doubly linked list.

If need for frequent addition or deletion, used linked list.

LinkedList also implements Queue and Deque, interfaces in java collections.

Thus, you have to use LinkedList instead of ArrayList if you methods from these interfaces, such as peek(), getFirst(), addLast(), etc.

Linkedlist uses more memory than ArrayList. Also more time consuming to find an element as you have to iterate.

Thus, if memory is an issue or there is a frequent need to find elements, linked list is not advised.

Declaration:

LinkedList ll = new LinkedList<>();

Or

List ll = new LinkedList<>();

Methods:

All methods in ArrayList exist in LinkedList, since they both implement List.

However, because it implements Queue and Deque interfaces as well, it as access to their methods. HOWEVER, YOU MUST DECLARE IT A LINKEDLIST AND NOT A LIST TO USE THESE METHODS.

Peek(), getFirst(), and getLast() do not remove element.

56
Q

File handling

A

Getting input from user is not always practical. Sometimes we need to read information from a file. Java provides classes and methods to work with files. To use, import java.io.*.

Classes I’ll focus on:

  • File
  • BufferReade
  • FileReader
  • BufferReader
  • BufferWriter
  • FileWriter
57
Q

Reading a text file

A

We use FileReader class. FileReader reads file as a stream of characters, one by one. TBC…

58
Q

Writing to a text file

A

We use the BufferWriter and FileWriter class.

59
Q

class hierarchy

A

LinkedList implements Collection, Lisr, Queue, and Deque

ArrayList implements List and Collection

TreeSet implements SortedSet, Set, and Collection

PriorityQueue implants Queue and Collection

Stack implements List and Collection

60
Q

Java Map hierarchy

A

Notable Classes that implements Map are Hashtable, Hashmap, TreeMap, and LinkedHashMap.

61
Q

Collection interfaces

A

Set

List

Queue

Deque