360 likes | 646 Views
Primitive types. logical : boolean textual : char integral: byte 8 bits -2 7 to 2 7 – 1 short 16 bits -2 15 to 2 15 – 1 int 32 bits -2 31 to 2 31 – 1 long 64 bits -2 63 to 2 63 – 1 floating: float 32 bits double 64 bits . Everything else.
E N D
Primitive types • logical : boolean • textual: char • integral: • byte 8 bits -27 to 27 – 1 • short 16 bits -215 to 215 – 1 • int 32 bits -231 to 231 – 1 • long 64 bits -263 to 263 – 1 • floating: • float 32 bits • double 64 bits Columbia University JETT
Everything else • Everything that is not a primitive type is a reference type • A reference variable contains a reference to an object • Circle sun = new Circle(); • allocates memory for this new object • initializes attributes sun • executes constructor • assigns reference to reference variable Columbia University JETT
Object-Oriented Programming • Each object has • its own memory • belongs to a class (instance of a class) • Class defines • attributes (defines state) • behavior (methods) • Building blocks of Java programs • Every program creates a class Columbia University JETT
Intro to Strings • String not built into Java • String is a class, part of java.lang package • Automatically imported • Declare: • String greeting; // note caps • Allocate space • greeting = new String ("hello world!"); • or • String greeting = new String ("hello world!"); • Strings are so common, we can do: • String greeting = "hello world!"; Java Elements
String Objects • Strings can be created implicitly by using a quoted string • String name = "Tom Jones"; • String s1 = "Hello"; • String s2 = "World!"; • Class - String • Object – s1 • or, by using + on two String objects to create a new one • String combo = s1 + " " + s2; • String is capitalized • String is a sequence of characters Java Elements
String Objects • Performing operations on objects is different than primitives • Call methods • Using variable name • s1.length() • System.out.println("Length of s1 = " + s1.length()); • Length of s1 = 5 • <variable>.<method name>(<expression>,<expression>,…,<expression>) Java Elements
String objects – method length • String s1 = “hello”; • String s2 = “how are you?”; • System.out.println(“Length of s1 = “ + s1.length(); • System.out.println(“Length of s2 = “ + s2.length(); • Length of s1 = 5 • Length of s2 = 12
String objects – method charAt • Zero based indexing • String s1 = "hello"; • h e l l o • 0 1 2 3 4 • s1.charAt(0) => h • s1.charAt(3) => l
String objects – method substring • substring(starting index, ending index+1) • String s2 = “how are you?”; • s2. substring(0,3) => how • s2.substring(8,12) => you?
String objects - index • Index – integer used to indicate location • Zero based • Beware of index • 0 <= index < length() • Out of bounds • any String method requiring an index will throw an IndexOutOfBoundsException if 0 <= index <= length() is violated • Exception – runtime error • Exception is thrown when an error is encountered
String • x = 45; x 45 • String is not a primitive type, class • String str; • str = “Java Programming”; str 2500 2500 Java Programming reference variable object • str = new String (“Java Programming”); • Reference variable
new • new is an operator • Causes the system to allocate space for object • Returns address • Instantiates a class object
Example of new • Scanner console = new Scanner(System.in); • String str = “Hello”; // = new String implied • int[] arr = new int[20]; • Time time1 = new Time;
String str = "Hello"; • Reference variable • Variables that store the address • Any variable declared using a class is a reference variable • str is a reference variable of type String • Memory space with Hello is an object or instance of type String
Strings are immutable str 2500 2500 Java Programming Cannot change value at address 2500 Strings are immutable (once created they cannot be changed) New assignment creates new object str = “Hello There!”; str 3850 3850 Hello There! str Hello There!
Garbage collection • “Java Programming” gets reclaimed later • Happens automatically • An object is eligible for garbage collection when there are no more references to that object. • References that are held in a variable are usually dropped when the variable goes out of scope. • Or, you can explicitly drop an object reference by setting the variable to the special value null.
Summary • Two types of variables in Java • Primitive • Store data directly into memory • Reference • Store address of object containing data • An object is an instance of a class • new is used to instantiate an object
Packages, Classes, Methods, import • import packageName.*; • java.lang- provides fundamental classes • String, Math • import java.util.*; // compiler determines relevant classes • import java.util.Scanner; Java Elements
Console Input • Scanner is a class • Need to import java.util import java.util.*; //allows use of Scanner class Scanner console = new Scanner (System.in); • Creates object console (can use any identifier name) • Associates console with standard input device • System.in – standard input device Java Elements
Console input • console.nextInt() // retrieves next item as an integer • console.nextDouble() //retrieves next item as double • console.next() //retrieves next item as string • console.nextLine() // retrieves next item as string up to newline • ch = console.next().charAt(0); // reads a single character • Inappropriate type -> exception Java Elements
import java.util.*; public class BMICalculator { public static void main(String [] args) { double height; double weight; double bmi; Scanner console = new Scanner(System.in); System.out.println("Enter height"); height = console.nextDouble(); System.out.println("Enter weight"); weight = console.nextDouble(); bmi = weight/(height * height) * 703;//No range checking // so this value could // divide by zero. //more on this later System.out.println("Current BMI:"); System.out.println(bmi); } } Java Elements
Java application program import statements if any publicclassClassName { declare names constants and/or stream objects public static void main(String[] args) { variable declarations executable statements } } Java Elements
Predefined classes and methods • Predefined classes • Contain predefined methods • Package contains classes • static method – belongs to class, can be used by calling the name of the class • Non-static method – belongs to object of class
Using predefined classes and methods • class Math • import java.lang.*; // package, automatically // imported • Math contains all static methods • Math.pow(2, 3) // method call • // 2 arguments . member access operator
Math methods • static double abs (double) Returns the absolute value of the argument • static float abs (float) Returns the absolute value of the argument • static int abs (int) Returns the absolute value of the argument • static long abs (long) Returns the absolute value of the argument • static double exp (double) Returns e raised to the power of the argument • static double log (double) Returns the natural logarithm of the argument • static double pow (double base, double exp) Returns the base raised to the exp power • static double random () Returns a pseudorandom number in the range [0, 1) • static long round (double) Returns the nearest integer to the argument • static int round (float) Returns the nearest integer to the argument • static double sqrt (double) Returns the square root of the argument
Formatting output with printf • System.out.printf (formatString); • System.out.printf (“Hello There!”); • System.out.printf (formatString, argumentList); • System.out.printf (“There are %.2f inches in %d centimeters.%n”, centimeters/2.54, centimeters); • %.2f and %d – format specifiers • Each format specifier in formatString must have one corresponding argument in the argumentList • When outputting the format string, the format specifiers are replaced with the formatted values of the corresponding arguments
%[argument_index$][flags][width][.precision]conversion • Expressions in square brackets are optional • argument_list - integer indicating the position of the argument in the argument list • flags – set of characters modifies the output format • width – integer indicating minimum number of characters to be written to the output • precision – integer used to restrict the nymber of characters • conversion – character indicating how the argument should be formatted
double x = 15.674; double y = 235.73; double z = 9525.9864; System.out.printf("x = %.2f %n", x); System.out.printf("y = %.2f %n", y); System.out.printf("z = %.2f %n", z); x = 15.67 // note rounding y = 235.73 z = 9525.99
double x = 15.674; double y = 235.73; double z = 9525.9864; System.out.printf("x = %.3f %n", x); System.out.printf("y = %.3f %n", y); System.out.printf("z = %.3f %n", z); x = 15.674 y = 235.730 z = 9525.986
int num = 96; rate = 15.50; System.out.println("123456789012345"); System.out.printf("%5d %n", num); System.out.printf("%5.2f %n", rate); System.out.printf("%5d%6.2f %n", num, rate); System.out.printf("%5d %6.2f %n", num, rate); 123456789012345 96 15.50 96 15.50 96 15.50
width represents minimum System.out.printf("%1d %n", 8756); 8756 System.out.printf("%2d %n", 8756); 8756 System.out.printf("%3d %n", 8756); 8756 System.out.printf("%4d %n", 8756); 8756 System.out.printf("%5d %n", 8756); 8756
Exercises • How does the variable of a primitive type differ from a reference variable? • What is an object? • Consider the following statements: String str = “Going to the park.”; char ch; intlen; int position; • What value is stored in ch by the following statement? ch = str.charAt(0); b. What value is stored in ch by the following statement? ch = str.charAt(10); c. What value is stored in len by the following statement? len = str.length(); d. What value is stored in position by the following statement? position = str.indexOf(‘t’); e. What value is stored in position by the following statement? position = str.indexOf(“park”);
4. Consider the following statements: String str = “Going to the amusement park.”; char ch; intlen; int position; What is the output of the following statements? • System.out.println (str.substring (0,5)); • System.out.println (str.substring (13,22); • System.out.println (str.toUpperCase()); • System.out.println (str.toLowerCase()); • System.out.println (str.replace(‘t’,’*’));
5. Consider the following statements: double x = 75.3987; double y = 987.89764; What is the output of the following statements? • System.out.printf(“%5.2f %n”, x); • System.out.printf(“%6.2f %n”, y); • System.out.printf(“%7.3f %n”, x); • System.out.printf(“%6.3f %n”, y);