Download presentation
Presentation is loading. Please wait.
Published byMargaret McDaniel Modified over 9 years ago
1
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/20) Java Basics Joel Adams and Jeremy Frens Calvin College
2
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(2/20) Classes Last time, we saw that classes play a central role in Java. Pattern: AccessMode class TypeName { Declarations } where AccessMode is either public or private. Example: public class Person { // declarations of Person attributes } Java style: Names of classes begin with a capital letter.
3
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(3/20) Java Primitive Types Java has two kinds of types: primitive vs. reference types. The four most commonly used primitive types include: TypeBitsStores int 32integers (…, -3, -2, -1, 0, 1, 2, 3, …) double 64real numbers (-3.5, 0.0, 1.67, 3.0e8, …) char 16characters ('A', 'a', '?', '!', '1', '2', '+', '-', …) boolean ??logical values ( false, true ) Java also provides: byte (8 bit char), short (16 bit int.), long (64 bit int.), and float (32 bit real).
4
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(4/20) Variable Declarations Java requires that all variables be declared using a type. Pattern: Type VariableName [ = InitialValue ] ; Examples: intmyAge = 45; // sigh! doublemyHeight = 6.0; // feet charmyGender = 'M'; // male booleanamMarried = true; Multiple variables of the same type can be declared together: intwidth = 100, height = 200, depth = 300;
5
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(5/20) Primitive type variables can be used in the usual way: Primitive Numeric Expressions inti = 3, j = 5; System.out.println(j+i); // 8 System.out.println(j-i); // 2 System.out.println(j*i); // 15 System.out.println(j/i); // 1 System.out.println(j%i); // 2 doublex = 3.0, y = 5.0; System.out.println(y+x); // 8.0 System.out.println(y-x); // 2.0 System.out.println(y*x); // 15.0 System.out.println(y/x); // 1.6666667
6
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(6/20) Mathematical Methods Java’s Math class provides assorted constants and methods, including: Math class Note that these are messages sent to a class ( Math ). Math.abs(v) // the absolute value of v Math.pow(x, y) // x raised to the power y Math.sqrt(x) // the square root of x Math.rint(x) // the int closest to x Math.round(x) // the long closest to x Math.max(x, y) // maximum of x and y Math.min(x, y) // minimum of x and y Math.exp(x) // e raised to the power x Math.log(x) // natural logarithm of x
7
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(7/20) Assignment Statements To change the value of a variable, use an assignment… Pattern: Variable = Expression ; where Expression, Variable are each of the same type. Examples: energy = mass * Math.pow(C, 2); circumf = 2.0 * Math.PI * radius; hypot = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2) ); A semicolon must be present at the end of every assignment.
8
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(8/20) Short-Cut Arithmetic Operators Some assignments are used so frequently, Java provides a short-cut for them: Instead of Writing:You Can Write: var = var + 1;var++; or ++var; var = var - 1; var--; or --var; var = var + x;var += x; var = var - x;var -= x; var = var * x;var *= x; var = var / x;var /= x; Assignments can also be chained together: w = x = y = z = 1; // init. all to 1
9
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(9/20) Boolean Expressions Boolean expressions are built using the relational operators: Use the logical operators to combine relational expressions: x == y // equality (gotcha) x != y// inequality x < y// less-than x <= y// less-than-or-equal-to x > y// greater-than x >= y// greater-than-or-equal-to 0 < x && x < 101// AND x 100// OR !(0 < x && x < 101)// NOT
10
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(10/20) Reference Types In contrast to int, char, …; a class is a reference type… Variables of that type (called handles) store addresses. String is a commonly-used reference type: String s = null; // s is a handle s = "Hi there"; char ch = '!'; // ch is primitive s = s + ch; // + appends s += ch;// append shortcut System.out.println(s); // Hi there!! char firstChar = s.charAt(0), // 'H' lastChar = s.charAt( s.length()-1 ); You can send a message (see API) to an object via its handle.
11
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(11/20) Methods We saw last time that classes usually contain methods… -- the methods in a class correspond to the messages to which an object of that class will respond. Pattern: AccessMode class TypeName { AccessMode [Kind] ReturnType methodName ( ParamDecs ) { Statements } Method-names style: each word except the first is capitalized.
12
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(12/20) Each Java program must have a method named main() : The main() Method public class MyProgram { public static void main(String [] args) {... } A static method is a message sent to a class (so they’re called class methods): double result = Math.sqrt(x); A non-static method is a message sent to an object (an instance of a class, so they’re called instance methods): int length = s.length();
13
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(13/20) Other Methods Non-main methods follow the same pattern: Example: class Sphere {... } public static double volume(double radius) { return 4.0 * Math.PI * Math.pow(radius, 3) / 3.0; } public static double mass(double radius, double density){ return density * volume(radius); } If a method has a non-void return-type, it must use a return statement to return a value.
14
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(14/20) Control Structures: if Java’s if statement provides basic selective execution: Example: if (s == null || s.equals("")) { System.err.println("error"); System.exit(1); } else System.out.println(s); If you are selecting a single statement, you need no braces; if you are selecting multiple statements, you need braces. Style: Many people just use braces all the time.
15
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(15/20) The Statement following an if ’s else can be another if : Multibranch if Example: public static char computeGrade(int score) { if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; return grade; } Style: Java doesn’t care (much) about lines or white space…
16
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(16/20) Control Structures: switch Java’s switch statement also provides multibranch execution: Example: switch ( score / 10 ) { case 10: case 9: grade = 'A'; break; case 8: grade = 'B'; break; case 7: grade = 'C'; break; case 6: grade = 'D'; break; default: grade = 'F'; } Must be int-compatible break statements are needed to avoid “drop- through” behavior…
17
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(17/20) Control Structures: loops Java provides 3 basic loops: while, do, and for. The while loop is a test-at-the-top loop: Example: s = myTextField.getText(); while ( invalidValue(s) ) { statusLine.setText("invalid value"); s = myTextField.getText(); } Or: while ( true ) { s = myTextField.getText(); if ( validValue(s) ) break; statusLine.setText("invalid value"); }
18
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(18/20) Control Structures: do The do loop is a test-at-the-bottom loop: Example: public static void pause(double seconds) { long startT = System.currentTimeMillis(); if (seconds > 0) { long currentT = 0, millisecs = (long)(1000*seconds+0.5); do { currentT = System.currentTimeMillis(); } while (currentT - startT <= millisecs); } else { System.err.println("seconds is negative"); }
19
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(19/20) Java’s for loop is an amazingly flexible counting loop: Control Structures: for Examples: for (int i = 1; i <= 100; i++) { System.out.println(i); // up by 1s } for (double d = 0.5; d >= -0.5; d -= 0.02) { System.out.println(d); // down by 0.02 } for (Node n = aList.getFirstNode(); n != null; n = n.getNextNode()) { System.out.println(n); // traverse a list }
20
2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(20/20) Summary Java categorizes types as primitive or reference. Java expressions consist of: Applying operators to primitive type values Sending messages to reference type values (objects). Static methods are messages to classes. Non-static methods are messages to objects. Java provides a rich set of control structures: If and switch statements for selection; While, do, and for statements for repetition.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.