Sie sind auf Seite 1von 8

Java Exam Prep (Quick Notes)

Command
System.out.print();

What it does
Prints stuff out

Example
System.out.print("Hello world"); int dog = 53;

Comments
Use 'println' to print something followed by a new line Creates an int variable called dog which holds the integer 53 Creates a string variable called hi which holds the string Hello Adding the -- or ++ before i.e. -i/++i will add 1 first then do the command If i is equal to 10, do this; if it's not equal to 10 but is equal to 5, do this; else if it doesn't meet any condition, do this

Variables

Saving ints/Strings etc. in a variable

Incrementing and Decrementing

Increas/decrease a value by 1

String hi = "Hello"; int i = 0; I++ (adds 1) I-- (subtracts 1) if(i == 10){ //enter action } else if(i ==5) { //enter action } else{ //enter action } String person; switch(person){ case "john": system.out.print("hello john"; break; case "cassie": system.out.print("hello cassie"; break; deafult: system.out.print("i don't know your name"); break; } System.out.print ((gender.equals("male")) ? "Mr" : "Ms");

If-statements if(){ }else if(){ }else(){ } Switch-statements switch(variable to test){ case test condition: //action statement break; default: //action if no condition is true break; }

Basic way to test a condition: sees if something is true/false then takes action

Like if statements, but easier to use if you have loads of conditions - you can have as many cases as you like

Tests the variable 'person'. If person = John, print Hello John. If person = Cassie, print Hello Cassie. If person equals none of the above print I don't know your name

Ternary operator (Test condition) ? if true action : if false action; For loop for( start; condition; end){ //what to repeat } While loop while(loop condition){ //action to repeat}

Short quick way to test a condition

If gender = male, print Mr, else print Ms

Repeats a section of a program a fixed number of times

For(int i=0; i <10; i++){ //action to repeat }

Start with i as 0. Repeat this loop as long as i is less than 10. Increase i by 1 each time you loop While age is less than 21, repeat this action - part of the action tells the while loop to add 1 to age each time it loops

Like the for loop but only takes one 'argument'. the loop condition is changed inside the loop i.e ->>>

while (age<21){ //action to repeat age++; }

Do-while loop do{ //action to repeat }while(loop condition);

Like the while loop but the action to repeat happens before the loop takes place to insure that the action happens at least 1 regardless of the loop

targetLoop: do{ counter++ }while(counter<10);

Increase the counter by 1 then commence the for loop. in other words. Increase the counter by 1 only while the counter is less than 10 targetLoop is the name of the loop we just created. You name loops by adding name followed by a ':' just before the loop Creates a String array called hi which contains 3 items. hello = index no. 0 bonjour = 1 hola = 2 etc.

Arrays arrayType[] nameOfArray = {items in array}; OR arrayType[] nameOfArray = new arrayType[no. of items in the array] arrayname[index] = ..;

Sort of like a list, it stores data; This is an array with an unknown no. of items

String[] hi = {"hello", "bonjour", "hola"}; OR String[] hi = new String[10] (this is an array that only contains 10 elements) hi[0] "hello"; hi[1]="bonjour"; hi[2]="hola"; etc. (this is how you set each item in the array to something)

This creates an array with a set number of items

Can use sort() to sort an array in ascending numerical order (alphabetical for strings) import java.util*; Arrays.sort(arrayName);

Multidimensional Arrays arrayType[][] arrayName = {items in array1}{array2}; OR arrayType[][] arrayName = new arrayType[no. of items in array1][array2]; arrayName[index] = ...; Objects (read into OOP to understand this further) className objectName = new className(); objectName.method

Arrays with more than one dimension - one stores x the other stores y (i.e. coordinates (x,y))

Boolean[][] point = new boolean[50][50];

Creates a boolean 2 dimensional array called point. Each dimension contains 50 items. Here we are setting each point in the array to a boolean value: point(3,31) = true point(32,1) = true point(12,21) = false etc..

point[3][31] = true; point[32][1] = true; point[12][21] = false; etc.

Basically, calling a class inside a different class

Class A - contains a method called CD Class B Inside B:

First you create a new object of the class you want to use, in this case class A. Then to use a method from class A we call the object name (newObj) followed by the class we want to use

Doesn't have to be a method; you could call and change a variable

A newObj = new A(); newObj.CD;

Name;

Casting

Vectors Vector<dataType> vic = new Vector<dataType>();

Converting one data type to another A data structure which holds objects of the same class

Int xNum = 103; Byte val = (byte) xnum; Vector<String> vic = new Vector <String>();

The int 103 gets stored as a byte in the variable 'val' Creates a new string vector called vic. Adds the string 'Hello' to the vector vic using the add keyword etc. Hello = index no. 0 Bye = index no. 1 etc. Just like lists and arrays Takes the item stored in vic under index no. 1 (Bye) and stores it in the string variable 'name' contains() keyword used to see if an item is inside the vector vic - this checks if "Bye" is in vic

vic.add("Hello"); vic.add("Bye");

String name = vic.get(1);

vic.contains("Bye");

vic.remove(0); OR vic.remove("Hello"); Exceptions try{ // statements that might cause the exception }catch(Exception e){ //what to do when an exception occurs }finally{ //statements to execute after everything regardless of if there's an exception or not } Input Streams FileInputStream() a constructor method that can be called to read data Exceptions are sort of like errors, you need to be able to catch them if they appear float sum = 0; for (int i = 0; i < arguments.length; i++){ try{ sum = sum + Float.parseFloat(arguements[i ]); }catch(NumberFormatExcepti on e){ System.out.println(arguments [i] + " is not a number."); } }

remove() gets rid of an item in a vector Catches the exception in case the item entered is not a float then prints whatever is entered (arguments[i]) is not a number. The thing that causes the exception is within the try{} section

You can throw an exception after catching it so you don't have to deal with it

throw e; In other words, reading files try { File cookie = new File("cookie.txt"); //creates object for a file called 'cookie.txt' in current folder. FileInputStream stream = new FileInputStream(cookie); System.out.println("Length of Check page 6 & 7 of this doc for keywords and better eg First create a file object (the file you're going to read) Second, create a stream object (FileInputStream to read files)

Output Streams FileOutputStream()

Writing to a file (includes creating a new file)

file: " + cookie.length()); } catch (IOException e) {System.out.println("Could not read file."); } try{ File file = new File("pro.txt"); FileOutputStream fileStream = new FileOutputStream(file); write(fileStream, "username=max"); write(fileStream, "score=12550"); // '' write(fileStream, "level=5"); } catch (IOException ioe){ System.out.println("Could not write file"); }

Finally, you can read the file or display its length etc. (check keywords)

First create a File object that's associated with an output stream Second, FileOutputStream --> says: write to fileStream 'username=max'

catches exception in case the file doesn't exist Check notes on page 6 for more detail! And page 8 for better eg

Random but important! .length String[] array = {"hi", "bye", "my", "rye"}; System.out.print(array.length); Import java.util.*; Random dice = new Random(); dice.nextInt(6);

Description Gets the length of something This should return the '4' since there are 3 items in the array Generates a random number which is saved as an object called 'dice' This tells the program that you want a random number from 0 to 5 Random number from 1-6 (1+ makes the count start from 1 i.e. 50+ makes the count start from 50) Random number from 51 to 70 (51+19 = 70)

1+ dice.nextInt(6);

51+ dice.nextInt(19); (This says start from 51 and go on to the next 19 integers) The 'this' keyword

this bongo;

extends keyword public class tuna extends fish;

Used to refer to a variable method within the class you are in; let's say there are 2 classes, A and B and both contain a variable called bongo you are in Class B and want to refer to the bongo variable in your current class so you use the 'this' keyword so the program knows which bongo you're talking about This is used when dealing with inheritance, subclasses, superclasses etc.

Read into inheritance to find out more

this tells the program that the class tuna is a subclass of the class fish (this makes fish the superclass) The 'super' keyword

(lecture 18 or 24 Hours Java chapter 12)

public readfiles(String name, int length){ super(name, length); this tells the program that you want to use the name and length variables from the superclass rather than creating/rewriting them out

Just like the 'this' keyword but used for superclasses. Above we said that tuna is a subclass of fish(the superclass). When you are in the class tuna and want to refer to tuna's superclass methods/variables (fish's methods/variables) you use the word 'super' keyword

Special Characters (used in a string) \' \" \\ \t \b \n Example of usage:

Display Single quotation Double quotation Backslash Tab Backspace Newline System.out.print("Hello \n How are you"); This adds a newline after the word Hello

Special Characters (mainly in loops/ if statements etc.) > < == != >= <= && ||

Display Greater than Less than Equal to Not equal to Greater or equal to Less or equal to And Or

Imports import java.io.*; import java.util.*;

Description Input-output classes Data structures i.e. time, Scanner, random, maths classes etc.

Converting toString() int aInt = 1; String aString = Integer.toString(aInt); parseInt()

Description Convert any number type to String

Convert String to int

String aString = "78"; int aInt = Integer.parseInt(aString); parseDouble() etc. toCharArray() String hi = "hello world"; char[] yo = hi.toCharArray(); getBytes() i.e. String name = "sadfasdsdsdad"; byte[] nameBytes = name.getBytes();

Convert String to double etc. Convert String to char array

converts txt to bytes in an array

Reading/Writing Files Keywords exists() -> checks if file exists getName() -> gets the name of the file as a String length() -> gets the size of a file as a long value createNewFile() -> creates a file of the same name if it doesn't exist already delete() -> deletes the file renameTo(File) -> renames the file using the name of the File object as an argument listFiles() -> see what files are inside a folder skip() -> skips the number of bytes entered in the ()

Writing Files Info FileInputStream and FileOutputStream = classes that work with byte streams FileReader and FileWriter = classes that work with character streams To write stuff to a stream you need to create a File object that's associated with an output stream Output stream can be done in 2 ways: - Append existing file: call 'FileOutputStream()' with 2 arguments (File object representing the file and boolean 'true') - added text goes to end of the file - Write to a new file: call 'FileOutputStream()' with 1 argument (the File object (as its only object)) After you call an output stream, you use the 'write()' method: - write() with a byte as its only argument to write that byte to the stream - write() with a byte array as only argument to write entire array to stream - can write individual parts of an array by doing 'write(byte[], int, int);' -> name of array, element no. to start writing from, no. of bytes to write i.e. if an array had 10 elements -> write(data, 5, 5) => writes the last 5 elements of the array 'data'

READER EXAMPLE
import java.io.*; public class ID3Reader { public static void main(String[] args) { try{ File song = new File("Colbie Caillat - You Got Me.mp3"); // creates the object (looking at the file specified) FileInputStream file = new FileInputStream(song); // reads the file and stores as 'file' (opens the file) int size = (int) song.length(); // saves the size of the file (stored in object song) as size file.skip(size - 128); //skips to the last 128 bytes byte[] last128 = new byte[128]; //creates a byte array called last128 which contains 128 elements file.read(last128); // reads the last 128 bytes of the file through the array last128 String id3 = new String(last128); // array is used to create a string object String tag = id3.substring(0, 3); // first 3 characters in the string are TAG if (tag.equals("TAG")){ System.out.println("Title: " + id3.substring(3,32)); System.out.println("Artist: " + id3.substring(33,62)); System.out.println("Album: " + id3.substring(63,91)); System.out.println("Year: " + id3.substring(93,97)); //substring method called to display portions of the string (ID3 format always puts artist, song, title and year in the same positions in the last 128 bytes) } else { System.out.println(song + " does not contain" + " ID3 info."); } file.close(); // file is closed } catch (Exception e){ // catches exception where file doesn't exist System.out.println("Error - " + e.toString()); } } }

WRITER EXAMPLE
import java.io.*; public class ConfigWriter { String newline = System.getProperty("line.separator"); // creates a line separator object ConfigWriter(){ try{ File file = new File("program.properties.txt"); //create file object parameters hold the file to create/write to FileOutputStream fileStream = new FileOutputStream(file); //create an outputStream with the file object ( the file to write to) in the parameters write(fileStream, "username=max"); //says: write to fileStream username=max write(fileStream, "score=12550"); // '' write(fileStream, "level=5"); // '' } catch (IOException ioe){ System.out.println("Could not write file"); //catches exception in case it doesn't exist } } void write(FileOutputStream stream, String output) //new method called write which takes the parameters of an OutputStream and a String throws IOException{ //throws any exceptions output = output + newline; //adds a new line after the String entered i.e. write(nameOfStream, "hello") -> takes the string hello and adds a new line at the end byte[] data = output.getBytes(); // new byte array which converts the String saved in output into a byte and saves it an the array stream.write(data, 0, data.length); // writes data in the array 'data' to stream starting from element '0' till the end of the array } public static void main(String[] args){ ConfigWriter cw = new ConfigWriter(); //calls the configWriter method for it to run } }

Das könnte Ihnen auch gefallen