DP Computer Science Unit 4.3: Intro to programming Installing Java Software & websites JDK (Java development kit) download: http://www.oracle.com/technetwork/java/javase/ Tradition For a full IDE (integrated development environment): https://www.jetbrains.com/idea/ For a web based environment for practice: https://repl.it/languages/java Useful reference site: https://www.tutorialspoint.com/java/ https://stackoverflow.com/ 1
Hello world Boiler plate (get used to it it s Java) Print & input Variables int a = 1; float f = 1.0; String s = "hello"; boolean b = false; 2
Printing System.out.print() System.out.println() Eg: System.out.println("Hello world"!); Input java.util.scanner reader = new java.util.scanner(system.in); String t = reader.nextline(); Or: String message = "Hello world"; System.out.println( message ); Input & print example java.util.scanner reader = new java.util.scanner(system.in); Numbers System.out.print( "What's your name?" ); String personname = reader.nextline(); System.out.println( "Hello " + personname ); 3
Data types Numerical operations int a = 1; double d = 1.0; String s = "hello"; boolean b = false; int a = 5; int b = 4; System.out.println( a + b ); System.out.println( a b ); System.out.println( a * b ); System.out.println( a / b ); System.out.println( a % b ); // addition // subtraction // multiplication // division // modulus (remainder) Integer v float division? PEMDAS int a = 20; int b = 6; System.out.println( a / b ); System.out.println( a % b ); System.out.println( 2 + 4 * 3 ); // 14 or 18? double c = 20; double d = 6; System.out.println( c / d ); System.out.println( c % d ); 4
Inputting numbers java.util.scanner reader = new java.util.scanner(system.in); String t = reader.nextline(); int i = reader.nextint(); double d = reader.nextdouble(); Input number example java.util.scanner reader = new java.util.scanner(system.in); System.out.print("Type a number:"); int i = reader.nextint(); System.out.print("You typed "); System.out.print( i ); System.out.print(", the next number is "); System.out.println( i+1 ); Casting (converting) int num = Integer.parseInt( str ); int num = (int)math.round( d1 ); double d1 = Double.parseDouble( str ); double d1 = (double)i; String str = Integer.toString( num ); String str = Double.toString( d ); // String to int // double to int // String to double // int to double // int to String // double to String If then else 5
If / If else / If else if else Conditions: Comparing numbers if ( condition ) { if ( condition ) { else { if ( condition ) { else if ( condition ) { else { (a == b) IS EQUAL TO (a!= b) IS NOT EQUAL TO (a < b) IS LESS THAN (a <= b) IS LESS THAN OR EQUAL TO (a > b) IS GREATER THAN (a >= b) IS GREATER THAN OR EQUAL TO Conditions: Comparing strings Conditions: Multiple TESTING EQUALITY OF VALUE Objects.equals(s1, s2) s1.equals(s2) USE THIS OLD METHOD YOU'LL SEE USED ONLINE ( condition1 && condition2 ) AND ( condition1 condition2 ) OR (! condition1 ) NOT COMPARING ORDER OF VALUE s1.compareto(s2) == 0 when string values match == negative when s1 is alphabetically 1 st == positive when s1 is alphabetically 2 nd 6
For ever while I say so For & while loops for ( initialization ; comparison ; iteration ) { instructions(); while ( comparison ) { instructions(); Exactly the same for ( int i=0 ; i<10 ; i++ ) { System.out.println( i ); int i=0; while ( i<10 ) { System.out.println( i ); i++; How long is a piece of string? 7
String manipulation String s1 = "hello"; String s2 = "What does the fox say?"; s1.length(); // 5 s1.charat(0); // "h" s1.codepointat(0); // 104 (unicode) s2.indexof("fox"); // 14 s2.lastindexof("fox"); // 14 s2.substring(14,17); // fox s2.replace("fox","goat"); // What does the goat say? String manipulation String s1 = "hello"; String s2 = "What does the fox say?"; s2.touppercase(); s2.tolowercase(); String s3 = "Hi there! " + s2; // WHAT DOES THE FOX SAY? // what does the fox say? // concatenation String[] words = s2.split(" "); // ["What","does","the","fox","say?"] String manipulation Want to change an individual letter inside a string? Unlike other languages, you can not do str[2] = 'x' or similar. Java Strings are immutable (unchangeable). Most "simple" solution... Making a list and checking it twice String myname = "halftime"; myname = myname.substring(0,4) + 'x' + myname.substring(5); System.out.println(myName); // halfxime 8
Arrays v ArrayLists ARRAYS Fixed in size Simple structure import java.util.arrays; You need to know both ARRAYLISTS Resizable More complicated to use import java.util.arraylist; Arrays: Declaring int[] primes = new int[10]; primes[0] = 1; primes[1] = 2; primes[2] = 3; primes[3] = 5; primes[4] = 7; primes[5] = 11; primes[6] = 13; primes[7] = 17; primes[8] = 19; primes[9] = 23; int[] primes = {1,2,3,5,7,11,13,17,19,23; Two ways to do the same thing. Plus/minus each method? Arrays: Using java.util.arrays import java.util.arrays; for (int item : primes) { System.out.println( item ); for (int i=0; i<primes.length; i++) { System.out.println( primes[i] ); Just for something different two different ways to do a for loop through an array. Plus / minus each approach? // Check if two arrays are filled with matching values if ( Arrays.equals( primes, other )) { System.out.println("The two arrays match"); // Sort an array in ascending order Arrays.sort( primes ); // Create a string listing the contents of the array // output: [1, 2, 3, 5, 7, 11, 13, 17, 19, 23] System.out.println( Arrays.toString( primes )); 9
ArrayList: Declaring ArrayList: Using ArrayList<String> alist = new ArrayList<String>(); alist.add("first"); alist.add("second"); String item = alist.get(2); int size = alist.size(); alist.remove(3); // Remove 4 th item (index==3) Collectionssort(alist); for (String item : alist) { System.out.println( item ); Converting Example include java.io.file; include java.utils.arraylist; include java.utils.scanner; Array to ArrayList ArrayList arrlist = new ArrayList<>(Arrays.asList(arr)) ArrayList to Array (assuming it is String change as appropriate) String[] arr = (String[])arrlist.toArray(new String[arrlist.size()]); // load contents of a file into an arraylist File f = new File("/path/to/filename.ext"); Scanner reader = new Scanner(file); ArrayList<String> content = new ArrayList<String>(); while (reader.hasnextline()) { content.add(reader.nextline()); reader.close(); 10
Functions Functions A function is a simple way of being able to re use code. In Java the basic rule of syntax is: public static returntype functionname(paramtype param1, ) { // insert code return value; Example: Quadratic formula sort of public static double quadratic(double a, double b, double c) { double x = ( -b + Math.sqrt( b*b - 4*a*c ) ) / ( 2*a ); return x; public static void main(string[] args) { double result = quadratic(2,-4,-8); System.out.println( result ); Example 2: Calculate average public static double average(int[] numbers) { int sum = 0; for ( int number : numbers ) { sum = sum + number; return( (double)sum / (double)numbers.length ); public static void main(string[] args) { int[] a = { 3, 6, 9, 5, 2, 6, 4, 7, 8 ; double result = average( a ); System.out.println( result ); 11
Example 3: Read a file public static String[] getfileasarray( String filename ) { try { File f = new File(filename); Scanner reader = new Scanner(f); ArrayList<String> content = new ArrayList<String>(); while (reader.hasnextline()) { content.add(reader.nextline()); reader.close(); return((string[])content.toarray(new String[content.size()])); catch (Exception e) { System.out.println("ERROR processing file "+filename); System.out.println(e.getMessage()); return(new String[0]); public static void main(string[] args) { String[] words = getfileasarray("dictionary.txt"); for (String word : words) { System.out.println(word); System.out.println("There were "+words.length+" words!"); 12