• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/61

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

61 Cards in this Set

  • Front
  • Back

Valid Comments in Java

Single Line (//)


multi-line (/* */)


Javadoc comment (/** */)

Java code is executed with this statement

main method:


public static void main(String[]args){




}

Redundant Imports

java.lang doesn't need to be imported


Wild card statements

Constructors

Creates Java objects. Has the same name as java class and no return type.


Example: public class Ending{


public Ending { }


}

byte type

8 bit. Numbers -128 to 127.

Octal, Hexadecimal and Binary

Octal (digits 0–7), which uses the number 0 as a prefix—for example, 017 BASE 10


Hexadecimal (digits 0–9 and letters A–F), which uses the number 0 followed by x or Xas a prefix—for example, 0xFF


Binary (digits 0–1), which uses the number 0 followed by b or B as a prefix—for example,0b10

Rules for Literals and Underscores

You can addunderscores anywhere except at the beginning of a literal, the end of a literal, right before adecimal point, or right after a decimal point.

Declaring multiple variables

Declare as many variables of same type in one line, as well as initialize them. eg.




boolean b1, b2; // Legal


String s1 = "1", s2; //Legal


double d1, double d2; // Not legal


int i1; int i2; // Legal


int i3; i4; // i3 legal i4 is not

Identifiers (Name of variable)

■ The name must begin with a letter or the symbol $ or _.


■ Subsequent characters may also be numbers.


■ Cannot use Java keywords eg. public, class, int

Order of Initialization

■ Fields and instance initializer blocks are run in the order in which they appear inthe file.


■ The constructor runs after all fields and instance initializer blocks have run.

Local Variable Scope and rules

■Must be initialized otherwise doesn't compile.


■ Scope ends at the end of block



Default values for:


boolean,


byte, short, int, long


float, double


char


All object references (everything else)

boolean: false


byte, short, int, long: 0 (in the type’s bit-length) float, double: 0.0 (in the type’s bit-length)


char: '\u0000' (NUL)


All object references (everything else): null

Ordering Elements in a Class

Package declaration EG. package abc;


Not required. First line in the file




Import statements EG. import java.util.*; Not required.Immediately after the package




Class declaration EG. public class C


Required. Immediately after the import




Field declarations EG. int value;


Not required. Anywhere inside a class




Method declarations eg. void method(){}


Not required. Anywhere inside a class

Garbage collection for Object

■ The object no longer has any references pointing to it.


■ All references to the object have gone out of scope.

finalize()

finalize() is only run when the object is eligible for garbage collection.

Numeric Promotion Rules

1. If two values have different data types, Java will automatically promote one of the valuesto the larger of the two data types.




2. If one of the values is integral and the other is floating-point, Java will automaticallypromote the integral value to the floating-point value’s data type.




3. Smaller data types, namely byte, short, and char, are first promoted to int any timethey’re used with a Java binary arithmetic operator, even if neither of the operands isint.




4. After all promotion has occurred and the operands have the same data type, the resultingvalue will have the same data type as its promoted operands.

Increment and Decrement Operators

pre-increment operator, the operator is applied first and the value returnis the new value of the expression. post-increment operator , then the originalvalue of the expression is returned, with operator applied after the value is returned.




eg.


int counter = 0;System.out.println(counter); // Outputs 0System.out.println(++counter); // Outputs 1System.out.println(counter); // Outputs 1System.out.println(counter--); // Outputs 1System.out.println(counter); // Outputs 0




int x = 3;


int y = ++x * 5 / x-- + --x;


y= 4 * 5 / 4 + 2;


x = 2


y = 7.

Casting Primitive Values

Required when larger numerical datatype to smaller numerical data type, or


converting from a floating-point number to anintegral value.




eg.




int x = (int)1.0;


short y = (short)1921222; // Stored as 20678


int z = (int)9l;


long t = 192301398193810323L;



OR, AND, EXCLUSIVE

And symbol &


Or Symbol |


exclusive ^

Equality Operator

1.Comparing two numeric primitive types. For example,5 == 5.00 returns true since the left side is promoted to a double.


2. Comparing two boolean values.


3. Comparing two objects, including null and String values


-Two references are equal if and only if they point to the sameobject, or both point to null.

Ternary Operator

booleanExpression ? expression1 : expression2

Switch statement contruction

switch(variableToTest) {


case constantExpression1:


// Branch for case1;


case constantExpression2:


// Branch for case2;


...


default:// Branch for default


}


Int and Integer, byte and Btye, short and Short, char and Character, String and enum values

Basic for statement

for(initialization; booleanExpression; update) {


// Body


}




1) Initialization statement executes


2)If booleanExpression is true continue, else exit loop


3)Body executes


4)Execute updateStatements


5)Return to Step 2

Basic for-each statement



for(datatype instance : collection)


{


// Body


}

Advanced Flow control - Nested flow control

int[][] myComplexArray = {{5,2,1,3},{3,9,8,9},{5,7,12,7}};


for(int[] mySimpleArray : myComplexArray) { for(int i=0; i


System.out.println(mySimpleArray[i]+"\t");


}


System.out.println();


}



Break statement

optionalLabel: while(booleanExpression) {


// Body


// Somewhere in loop


break optionalLabel;


}

Immutability

String object is created, it is not allowed to change.




String s1 = "1";


String s2 = s1.concat("2");


s2.concat("3");


System.out.println(s2); // = 12

String Pool

String name = "Fluffy";String name = new String("Fluffy");




The second says “No, JVM. I reallydon’t want you to use the string pool. Please create a new object for me even though it isless efficient.”

substring()

String string = "animals";System.out.println(string.substring(3)); // malsSystem.out.println(string.substring(string.indexOf('m'))); // malsSystem.out.println(string.substring(3, 4)); // mSystem.out.println(string.substring(3, 7)); // mals



equals() and equalsIgnoreCase()

equals() method checks whether two String objects contain exactly the same charactersin the same order.




equalsIgnoreCase() same as equals() but ignores case.

replace()

String replace(char oldChar, char newChar)String replace(CharSequence oldChar, CharSequence newChar)

trim()

removes whitespace from the beginning and endof a String.

StringBuilder class

mutable




StringBuilder sb1 = new StringBuilder();StringBuilder sb2 = new StringBuilder("animal");StringBuilder sb3 = new StringBuilder(10);


// tells java we have a 10 capacity string

indexOf()

String string = "animals";System.out.println(string.indexOf('a')); // 0System.out.println(string.indexOf("al")); // 4System.out.println(string.indexOf('a', 4)); // 4System.out.println(string.indexOf("al", 5)); // -1

delete() and deleteCharAt()

StringBuilder delete(int start, int end)StringBuilder deleteCharAt(int index)

Equality in Strings and Objects. Difference between == and equals

"==" checks if two references point ot the same object.


"equals" checks if what's inside the string is the same. EG.


String x = "Hello World";


String z = " Hello World".trim();System.out.println(x.equals(z)); // true but "x==z" is false

Multiple “Arrays” in Declarations

int[] ids, types; // Two int [] arrays


int ids[], types; //one ids array and one int variable

Sorting Arrays

Needs import statement:


import java.util.*; //or
import java.util.Arrays;


//Used like Arrays.sort(Array here);


Sorts ints correctly


Sorts Strings 1-9, UPPERCASE A-Z, lowercase a-z

Searching Arrays

Needs import statement:


import java.util.*; //or


import java.util.Arrays;


/* Used like


Arrays.binarySearch( Array here, index)); */



Rules:




Target element found in sortedarray--->


Index of match


Target element not found insorted array ------------->Negative value showing one smaller than thenegative of index, where a match needs to beinserted to preserve sorted order

Multi-Dimensional Array

int[][] vars1; // 2D array


int vars2 [][]; // 2D array


int[] vars3[]; // 2D array


int[] vars4 [], space [][]; // a 2D AND a 3D array

ArrayList

Have to import:


import java.util.* // import whole package OR


import java.util.ArrayList;




ArrayList list1 = new ArrayList();


ArrayList list2 = new ArrayList(10);


ArrayList list3 = new ArrayList(list2);


ArrayList list4 = new ArrayList();


ArrayList list5 = new ArrayList<>();


List list6 = new ArrayList<>();



add () method

For ArrayList,



boolean add (E element)


void add (int index, E element)



remove()

boolean remove (Object object)


E remove (int index)



Converting between Array and ArrayList

toArray() method used to turn ArrayList to Array.




Arrays.asList(Array) method used to turn Array to ArrayList.

Sorting ArrayList or List

Method:




Collections.sort(ArrayList arraylist);

First thing to do to use Dates and Times on


JAVA 8

import time classes




import java.time.*;

Classes of date and time

LocalDate


LocalTime


LocalDateTime

LocalDate of Method

public static LocalDate of(int year, int month, int dayofMonth)




public static LocalDate of(int year, MONTH month, int dayofMonth)

Methods in LocalDate, LocalTime, and LocalDateTime



Working with Periods

Period annually = Period.ofYears(1); // every 1 year


Period quarterly = Period.ofMonths(3); // every 3 monthsWorking with Dates and Times 147


Period everyThreeWeeks = Period.ofWeeks(3); // every 3 weeks


Period everyOtherDay = Period.ofDays(2); // every 2 days


Period everyYearAndAWeek = Period.of(1, 0, 7); // every year and 7 days

Formatting Dates and Times
/* Use DataTimeFormatter class - inside the java.time.format package */
 

/* Use DataTimeFormatter class - inside the java.time.format package */


Formatting Dates and Times - Simple example/ syntax





PARSING DATES AND TIMES TO STRING

DateTimeFormatter.ofPattern("MM dd yyyy");


LocalDate date = LocalDate.parse("01 02 2015", f);


LocalTime time = LocalTime.parse("11:22");


Syst.println(date); // 2015-01-02


Syst.println(time); // 11:22



Method Signature & declaration

ACCESS MODIFIERS

*public

*private


*protected


*Default (Package private) access

METHOD OPTIONAL SPECIFIER


*static


*abstract


*final


*synchronized

METHOD RETURN TYPE

ALLOWED:
int integer(){


return 9;


}


NOT ALLOWED:


int long(){


return 9L;


}



METHOD NAMES

SAME AS VARIABLE NAMES.


*ONLY LETTERS, NUMBERS, $ sign, or UNDERSCORE _


*CANNOT START WITH NUMBER

WORKING with Varargs

-Like arrays


-Must be the last element in parameter list


-Can only have one


EXAMPLE:


public static void walk(int x, int... nums){


sys.print(nums.length);


}


walk(1); // 0


walk(1, 2) // 1


walk(1,3,3)// 2


etc..







Applying Access Modifiers to methods

Private: Accessible within the same class


default: private and other classes in the same package


protected: default access and child classes


public: protected and classes in the other packages

Gotcha's of protected modifier:

See screenshot.

See screenshot.