Java data types Primitive data types integers byte
Java data types • Primitive data types • integers (byte, short, int, long) • floating point numbers (float, double) • boolean (true, false) • char (any symbol encoded by a 16 -bit unicode) • Objects- everything else An object is defined by a class. A class is the data type of the object. You can define your own objects or use predefined classes from library. 2022/1/2 COP 3330 Object Oriented Programming 1
Data Types • Each value in memory is associated with a specific data type. • Data type of a value determines: – size of the value (how many bits) and how these bits are interpreted. – what kind of operations we can perform on that data. • A data type is defined by a set of values and the operators you can perform on them. • Data Types in Java: – Primitive Data Types – Object Data Types 2022/1/2 COP 3330 Object Oriented Programming 2
Primitive Data • There are exactly eight primitive data types in Java • Four of them represent integers: – byte, short, int, long • Two of them represent floating point numbers: – float, double • One of them represents characters: – char • And one of them represents boolean values: – boolean 2022/1/2 COP 3330 Object Oriented Programming 3
Primitive Data Types • There are eight primitive data types in Java programming language. byte short int long } float double } integers floating point numbers (real numbers 0 char -- characters boolean -- boolean values 2022/1/2 COP 3330 Object Oriented Programming 4
Typing and Naming What kind of things a program can manipulate? Some of them are simple, like numbers. Others may be complex. Those are called objects. What is a type? A type specifies what a thing can do (or what you can do with a thing). Names are ways to refer to things that already exist. Every name has a type, which tells you what you can expect from the thing that the name refers to. 2022/1/2 COP 3330 Object Oriented Programming 5
Java numerical primitive types There are four separate integer primitive data types They differ by the amount of the memory used to store them. Internally, integers are represented using two’s complement representation (discussed later). 2022/1/2 COP 3330 Object Oriented Programming 6
boolean char true or false ‘x’, ‘ 6’, ‘’’, ‘u 006 A’ 16 bit unicode Example: int a=1, b=0; boolean bool=a<b; // bool is false char letter=‘a’; 2022/1/2 COP 3330 Object Oriented Programming 7
Literal 6 6 L 6 l 1, 000, 000 2. 5 (or 2. 5 e-2) 2. 5 F 2. 5 f ‘x’ ‘n’ ‘u 0039’ true “t. Hello World!n” 2022/1/2 Assigned type int (default type) long int double (default type) float char (new line) char represented by unicode 0039 boolean String (not a primitive data type!) COP 3330 Object Oriented Programming 8
Literals and identifiers • A literal is a thing itself. You can type it directly in appropriate place of the program. • An identifier is a name that uniquely identifiers a thing. Java is a strongly typed language. Each thing (variable ) must be declared. int my. Number; double real. Number; char first. Letter. Of. My. Name; boolean is. Empty; Appropriate storage space is allocated. If no value is specified, the value is initialized to 0, 0. 0, ‘u 0000’ (null character) and false by default. 2022/1/2 COP 3330 Object Oriented Programming 9
Assignment actually assigns value to a name my. Number=4; first. Letter. Of. My. Name=‘N’; is. Empty=true; Combination of declaration and assignment is called definition boolean is. Happy=true; double degree=0. 0; String s = “This is a string. ”; float x, y=4. 1, z=2. 2; 2022/1/2 COP 3330 Object Oriented Programming 10
int y=4, z=2; x=y/z; 2022/1/2 Syntax error COP 3330 Object Oriented Programming 11
Binary Numbers • Before we talk about primitive data types in Java programming language, let us review the binary numbers. • • • a sequence of 0 s and 1 s. two bits: 00 01 10 11 (four different values) three bits: 000 001 010 011 100 101 110 111 (eight different values) 8 bits (1 byte): 0000. . . 1111 (256 different values) n bits: 2 n different values 2022/1/2 COP 3330 Object Oriented Programming 12
Internal Data Representation of Integers • Two’s complement format is used to represent integer numbers. • Two’s complement format representation makes internal arithmetic processing easier. • In Two’s complement format: – positive numbers are represented as a straight forward binary number. – a negative value is represented by inverting all the bits in the corresponding positive number, then adding 1. s value (sign bit 0 for positive numbers, 1 for negative numbers) Ex: (byte) 00000110 (6) 11111001 + 1 = 11111010 (-6) invert all the digits – one’s complement 2022/1/2 COP 3330 Object Oriented Programming then add one 13
Characters • A char value stores a single character from Unicode character set. • A character set is an ordered list of characters. Each character is represented by a sequence of bits. • The Unicode character set uses 16 bits per character (65636 unique characters) and contains international character sets from different languages, numbers, symbols. • ASCII character set is a subset of the Unicode character set. It uses only 8 bits (256 characters). In fact, the first 256 characters of the Unicode character set are ASCII characters. – – 32 48 -57 65 -90 97 -122 space 0 to 9 A to Z a to z • Character literals: – ‘a’ ‘A’ ‘ 1’ ‘ 0’ ‘+’ – Note that ‘ 1’ and 1 are different literals (character and integer) 2022/1/2 COP 3330 Object Oriented Programming 14
Characters • A char variable stores a single character from the Unicode character set • A character set is an ordered list of characters, and each character corresponds to a unique number • The Unicode character set uses sixteen bits per character, allowing for 65, 536 unique characters • It is an international character set, containing symbols and characters from many world languages • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ', ' 'n' 15
Characters • The ASCII character set is older and smaller than Unicode, but is still quite popular • The ASCII characters are a subset of the Unicode character set, including: uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, , … carriage return, tab, . . . 16
Reserved Words • Reserved words are identifiers that have a special meaning in a programming language. • For example, – public, void, class, static are reserved words in our simple programs. • In Java, all reserved words are lower case identifiers (Of course we can use just lower case letters for our own identifiers too) • We cannot use the reserved words as our own identifiers (i. e. we cannot use them as variables, class names, and method names). 2022/1/2 COP 3330 Object Oriented Programming 17
Java reserved words • Data declaration: boolean, float, int, char • Loop keywords: for, while, continue • Conditional keywords: if, else, switch • Exceptional keywords: try, throw, catch • Structure keywords: class, extends, implements • Modifier and access keywords: public, private, protected • Miscellaneous: true, null, super, this 2022/1/2 COP 3330 Object Oriented Programming 18
/* Hello. World application program */ public class Hello. World // Class header { // Start class body public static void main(String argv[]) //main method { System. out. println(“Hello. World!”); } // end of main } // end Hello. World words that we make up ourselves 2022/1/2 COP 3330 Object Oriented Programming 19
/* Hello. World application program */ public class Hello. World // Class header { // Start class body public static void main(String argv[]) //main method { System. out. println(“Hello. World!”); } // end of main } // end Hello. World words that are reserved for special purposes in the language are called reserved words 2022/1/2 COP 3330 Object Oriented Programming 20
words that are not in the language, but were used by other programmers to make the library /* Hello. World application program */ public class Hello. World // Class header { // Start class body public static void main(String argv[]) //main method { System. out. println (“Hello. World!”); } // end of main } // end Hello. World 2022/1/2 COP 3330 Object Oriented Programming 21
Literals • Literals are explicit values used in a program. • Certain data types can have literals. – String literal – “Hello, World” – integer literals -12 3 77 – double literals – 12. 1 3. 45 – character literals – ‘a’ ‘ 1’ – boolean literals -true false 2022/1/2 COP 3330 Object Oriented Programming 22
Another Simple Console Application Program public class Test 2 { public static void main(String args[]){ // print the city and its population. System. out. println("The name of the city is ” + “Orlando”); System. out. println(“Its population is “ + 1000000); // Different usage of + operator System. out. println(“Sum of 5+4: “ + (5+4)); // Different output method – print System. out. print(“one. . ”); System. out. print(“two. . ”); System. out. println(“three. . ”); System. out. print(“four. . ”); } // end of main } // end of class 2022/1/2 COP 3330 Object Oriented Programming 23
Another Simple Application Program (cont. ) • The operator + is a string concatenation operator. – “abc”+”de” “abcde” – 1000000 is converted to a String (“ 1000000”) , and this string is concatenated with the string literal “Its population is”. • The operator + is also a regular add operator for numeric values. + in (5+4) is a regular add operator for numeric values. • In other words, the + operator is overloaded. • println prints its argument and moves to the next line. • prints its argument and it does not move to the next line. • The output of our program will be: The name of the city is Orlando Its population is 1000000 Sum of 5+4: 9 one. . two. . three. . four. . 2022/1/2 COP 3330 Object Oriented Programming 24
Applets • A Java application is a stand-alone program with a main method (like the ones we've seen so far) • An applet is a Java program that is intended to transported over the web and executed using a web browser • An applet can also be executed using the appletviewer tool of the Java Software Development Kit • An applet doesn't have a main method • Instead, there are several special methods that serve specific purposes • The paint method, for instance, is automatically executed and is used to draw the applets contents 2022/1/2 COP 3330 Object Oriented Programming 25
Applets • The paint method accepts a parameter that is an object of the Graphics class • A Graphics object defines a graphics context on which we can draw shapes and text • The Graphics class has several methods for drawing shapes • The class that defines the applet extends the Applet class • This makes use of inheritance, an object-oriented concept explored in more detail in Chapter 7 2022/1/2 COP 3330 Object Oriented Programming 26
Applets • An applet is embedded into an HTML file using a tag that references the bytecode file of the applet class • It is actually the bytecode version of the program that is transported across the web • The applet is executed by a Java interpreter that is part of the browser 2022/1/2 COP 3330 Object Oriented Programming 27
Java Applets Fundamentals Any applet: • should be embedded into html file <html> <applet code=“My. Applet. class” width=100 height=100> </applet> </html> • is executed by appletviewer or by Web browser you can run applet by the command: appletviewer file_name. html • extends Applet class from java. applet package 2022/1/2 COP 3330 Object Oriented Programming 28
import java. applet. Applet; public class My. Applet extends Applet { // applet body } extends keyword indicates that the class My. Applet inherits from Applet class. superclass Applet subclass My. Applet Inheritance relationship 2022/1/2 COP 3330 Object Oriented Programming 29
A programmer can use all capabilities from predefined class Applet in any subclass that extends Applet. java. lang java. awt Object public boolean equals(Object arg) public String to. String() Component public void set. Size(int w, int h) public void set. Background(Color c) Container public void paint (Graphics p) public void add(Component item, …) Panel Applet public public void void init() start() show. Status(String message) stop() destroy() My. Applet One branch of a Hierarchy tree 2022/1/2 COP 3330 Object Oriented Programming 30
A Simple Applet Program // Author: Ilyas Cicekli Date: October 9, 1997 // // A simple applet program which prints “Hello, World” import java. awt. *; import java. applet. Applet; public class Test 1 Applet extends Applet { public void paint (Graphics page) { page. draw. String(“Hello, World”, 50); } // end of paint method } // end of class 2022/1/2 COP 3330 Object Oriented Programming 31
A Simple Applet Program (cont. ) • We import classes from packages java. awt and java. applet. – From java. awt package, we use Graphics class. – From java. applet package, we use Applet class (and its methods). • Our new class Test 1 Applet extends the already existing class Applet. – Our class will inherit all methods of Applet if they are not declared in our method • We declare only paint method – it is called after the initialization – it is also called automatically every time the applet needs to be repainted • Event-driven programming – methods are automatically called responding to certain events • draw. String writes a string on the applet. – draw. String(string, x, y) – top corner of an applet is 0, 0 2022/1/2 COP 3330 Object Oriented Programming 32
A Simple Applet Program (cont. ) • To compile: – javac Test 1 Applet. java – if there is a mistake in our code, the Java compiler will give an error message. • To run: – appletviewer Test 1 Applet. html – It will print Hello, World in the applet window. – Test 1 Applet. html file should contain: <html> <applet code="Test 1 Applet. class" width=300 height=100> </applet> </html> 2022/1/2 COP 3330 Object Oriented Programming 33
A Simple Applet Program (cont. ) Output: 2022/1/2 COP 3330 Object Oriented Programming 34
Another Applet Program -- Man. Applet. java // A simple applet program which draws a man import java. awt. *; import java. applet. Applet; public class Man. Applet extends Applet { } public void paint (Graphics page) { page. draw. String("A MAN", 100, 30); // Head page. draw. Oval(100, 50, 50); page. draw. Oval(115, 65, 5, 5); // eyes page. draw. Oval(130, 65, 5, 5); page. draw. Line(125, 70, 125, 80); // nose page. draw. Line(120, 85, 130, 85); // mouth // Body page. draw. Line(125, 100, 125, 150); // Legs page. draw. Line(125, 150, 100, 200); page. draw. Line(125, 150, 200); // Hands page. draw. Line(125, 75, 125); page. draw. Line(125, 165, 100); } // end of paint method // end of class 2022/1/2 COP 3330 Object Oriented Programming 35
Another Applet Program (cont. ) Man. Applet. html <html> <applet code="Man. Applet. class" width=300 height=300> </applet> </html> draw. String(astring, x, y) writes the given string starting from the <x, y> coordinate. draw. Line(x 1, y 1, x 2, y 2) draws a line from <x 1, y 1> to <x 2, y 2> coordinate. draw. Oval(x, y, width, height) draws an oval with given width and height (if the oval were enclosed in a rectangle). <x, y> gives the top left corner of the rectangle. 2022/1/2 COP 3330 Object Oriented Programming 36
Output of Man. Applet 2022/1/2 COP 3330 Object Oriented Programming 37
JAVA API (Application Programming Interface) • The Java API is a set of a class libaries. • The classes of the Java API are grouped into packages. • Each package contains related classes. • A package may contain another packages too. • We can access a class explicitly: java. lang. System (. seperates packages and classes). Or, we can access all classes in a package at the same time: java. awt. * Some packages in the Java API. java. lang general support, it is automatically imported into all Java programs java. io perform a wide variety of input output functions java. awt graphics relelated stuff (awt-Abstract Windowing Toolkit) java. applet to create applets java. mathematical functions. . 2022/1/2 COP 3330 Object Oriented Programming 38
Class Libraries • A class library is a collection of classes that we can use when developing programs • There is a Java standard class library that is part of any Java development environment • These classes are not part of the Java language per se, but we rely on them heavily • The System class and the String class are part of the Java standard class library • Other class libraries can be obtained through third party vendors, or you can create them yourself 2022/1/2 COP 3330 Object Oriented Programming 39
Packages • The classes of the Java standard class library are organized into packages • Some of the packages in the standard class library are: 2022/1/2 Package Purpose java. lang java. applet java. awt javax. swing java. net java. util General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Network communication Utilities COP 3330 Object Oriented Programming 40
The import Declaration • All classes of the java. lang package are automatically imported into all programs • That's why we didn't have to explicitly import the System or String classes in earlier programs • The Random class is part of the java. util package • It provides methods that generate pseudo-random numbers • We often have to scale and shift a number into an appropriate range for a particular purpose 2022/1/2 COP 3330 Object Oriented Programming 41
import Statement • We can access a class by giving its full name such as java. awt. Graphics. But we will repeat this over and over again in our programs. • The import statement identifies the packages and the classes of the Java API that will be referenced in our programs. import package. class identify the particular package that will be used in our program. example: import java. applet. Applet import package. * we will be able to access all classes in that package. example: import java. awt. * 2022/1/2 COP 3330 Object Oriented Programming 42
Structure of a Console Application Program imported classes – You should at least import classes in java. io package. public class <your application name> { public static void main (String args[]) throws IOException { declarations of local variables and local objects (references) executable statements } other methods if they exist } Remember the file name should be < your application name>. java 2022/1/2 COP 3330 Object Oriented Programming 43
Structure of an Applet Program • imported classes – you should import at least Graphics and Applet classes public class <your class name> extends Applet { – declarations • you should declare all variables which will be used in your methods – declarations of methods in your application • Declarations of your own methods and the methods responding to events. • If a required method is needed but it is not declared, it is inherited from Applet class. Normally the free versions we get from Applet class. } 2022/1/2 COP 3330 Object Oriented Programming 44
Some Methods for Events Normally, you may declare following methods (or other methods) to respond to certain events: public void init() – it is called when your applet is started. -- It performs initialization of an applet. public void start() – it is called after init method and every time user returns to this applet. public void paint (Graphics g) -- it is called after the initialization. -- it is also called automatically every time the applet needs to be repainted. public void stop() -- it is called when the applet should stop public void destroy() -- it is called when the applet is destroyed 2022/1/2 COP 3330 Object Oriented Programming 45
Structure of a Method public <its type> <its name> ( <its arguments> ) { – declarations of local variables – executable statements } 2022/1/2 COP 3330 Object Oriented Programming 46
Wrapper Classes • For each primitive data type, there exists a wrapper class. • A wrapper class contains the same type of data as its corresponding primitive data type, but it represents the information as an object (an instance of that wrapper class). • A wrapper class is useful when we need an object instead of a primitive data type. • Wrapper classes contain useful methods. For example, Integer wrapper class contains a method to convert a string which contains a number into its corresponding value. • When we talk numeric input/output, we will use these wrapper classes. • Wrapper Classes: – Byte Short Integer Long Float Double Character Boolean Void 2022/1/2 COP 3330 Object Oriented Programming 47
An Object Data Type (String) • Each object value is an instance of a class. • The internal representation of an object can be more complex. • We will look at the object data types in detail later. an object of String • String literals: “my name” “ 123” String s 1, s 2; s 1 = “abc” s 2 = “defg”; System. out. println(s 1+s 2) s 1 abc s 2 defg an object of String 2022/1/2 COP 3330 Object Oriented Programming 48
The String Class • Every character string is an object in Java, defined by the String class • Every string literal, delimited by double quotation marks, represents a String object • The string concatenation operator (+) is used to append one string to the end of another • It can also be used to append a number to a string • A string literal cannot be broken across two lines in a program 49
String Class String(String str); //constructor char. At(int index); int compare. To(String str); String concat(String str); boolean equals. Ignore. Case(String str); int length(); String replace(char old. Char, char new. Char); String substring(int offset, int end. Index); String to. Lower. Case(); String to. Upper. Case(); 2022/1/2 COP 3330 Object Oriented Programming 50
String Concatenation • The plus operator (+) is also used for arithmetic addition • The function that the + operator performs depends on the type of the information on which it operates • If both operands are strings, or if one is a string and one is a number, it performs string concatenation • If both operands are numeric, it adds them • The + operator is evaluated left to right • Parentheses can be used to force the operation order 51
Escape Sequences • What if we wanted to print a double quote character? • The following line would confuse the compiler because it would interpret the second quote as the end of the string System. out. println ("I said "Hello" to you. "); • An escape sequence is a series of characters that represents a special character • An escape sequence begins with a backslash character (), which indicates that the character(s) that follow should be treated in a special way System. out. println ("I said "Hello" to you. "); 52
Escape Sequences • Some Java escape sequences: Escape Sequence Meaning b t n r " ' \ backspace tab newline carriage return double quote single quote backslash 53
String type • The type for arbitrary text • Is not a primitive data type, but Java has String literals • Strings are objects, represented by String class in java. lang pachage declaration • String name; name=new String (“ Hello World!”); name instantiation Hello World! • String name=new String(“Hello World!”); constructor 2022/1/2 COP 3330 Object Oriented Programming 54
public class String. Class { public static void main(String [] args) { String phrase=new String(“This is a class”); String string 1, string 2, string 3, string 4; char letter; int length=phrase. length(); letter = phrase. char. At(5); string 1=phrase. concat(“, which manipulates strings”); string 2=string 1. to. Upper. Case(); string 3=string 2. replace(‘E’, ‘X’); string 4=string 3. substring(3, 30); System. out. println(“Original string: ”+phrase); System. out. println(letter); System. out. println(“lengh is”+length); …. } 2022/1/2 } COP 3330 Object Oriented Programming 55
Arithmetic Expressions • Simple Assignment Statements: x = y + z; x = x * 5; • Some of Arithmetic Operators: + * / % 2022/1/2 addition subtraction multiplication division mod operator (remainder) COP 3330 Object Oriented Programming 56
Arithmetic operators op 1+op 2 addition op 1 -op 2 subtraction op 1*op 2 multiplication op 1/op 2 division op 1%op 2 modulo • op 1 and op 2 can be of integer or floating-point data types • if op 1 and op 2 are of the same type, the type of result will be the same • mixed data types arithmetic promotion before evaluation • op 1 or op 2 is a string + operator performs concatenation 2022/1/2 COP 3330 Object Oriented Programming 57
Arithmetic Expressions • An expression is a combination of operators and operands • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder + * / % • If either or both operands to an arithmetic operator are floating point, the result is a floating point 2022/1/2 COP 3330 Object Oriented Programming 58
Division • If the operands of the / operator are both integers, the result is an integer (the fractional part is truncated). • If one or more operands of the / operator are floating point numbers, the result is a floating point number. • The remainder operator % returns the integer remainder after dividing the first operand by the second one. • The operands of % must be integers. • Examples: 2022/1/2 13 / 5 13. 0 / 5 13 / 5. 0 2 2. 4 2/4 2. 0 / 4. 0 0 0. 5 6%2 14%5 -14%5 0 4 -4 COP 3330 Object Oriented Programming 59
% Quick Review of / and % Remember when both operands are integers, / performs integer division. This simply truncates your answer. Thus, -11/3 is -3 and 5/4 is 1, for example. The % operator simply computes the remainder of dividing the first operand by the second. If the first operand is negative then the answer will also be negative (or zero). If the first operand is positive, then the answer will also be positive (or zero. ) Here a few examples: 11%3 is 2 11%-3 is 2 -11 % 3 is -2 -11 % -3 is -2 If you are at all unsure how these work, please try a few out on your own, compile and run them. (This is as easy as running a program with the statement System. out. println(-11%-3); ) 2022/1/2 COP 3330 Object Oriented Programming 60
Operator Precedence x = x + y * 5; • // what is the order of evaluation? Operators in the expressions are evaluated according to the rules of precedence and association. – – Operators with higher order precedence are evaluated first If two operators have same precedence, they are evaluated according to association rules. Parentheses can change the order of the evaluations. Precedence Rules for some arithmetic operators: + - (unary minus and plus) * / % + - • Examples: x = a + b * c – d; x = (a + b) * c – d; x = a + b + c; 2022/1/2 right to lefthigher left to rightlower COP 3330 Object Oriented Programming x = ((a+(b*c))-d); x = (((a+b)*c)-d); x = ((a+b)+c); 61
Data Conversion • Because Java is a strongly typed language, each data value is associated with a particular type. • Sometimes we may need to convert a data value of one type to another type. • In this conversion process, we may use loose important information. • A conversion between two primitive types falls into one of two categories: – widening conversions usually do not loose information – narrowing conversions may loose information • A boolean value cannot be converted to any other primitive type. 2022/1/2 COP 3330 Object Oriented Programming 62
Data Conversions • • • 2022/1/2 Sometimes it is convenient to convert data from one type to another For example, we may want to treat an integer as a floating point value during a computation Conversions must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short) COP 3330 Object Oriented Programming 63
Java Widening Conversions • In widening conversions, they often go from one type to another type uses more space to store the value. • In most widening conversions, we do not loose information. – we may loose information in the following widening conversions: • int float 2022/1/2 long float long double From byte To short, int, long, float, double short int, long, float, double char int, long, float, double int long, float, double long float, double float double COP 3330 Object Oriented Programming 64
Widening Conversions (cont. ) • A widening conversion may automatically occur: int y = z = x; long y; double z; x; x + 1; // the result of the addition is converted into double x + 1. 0; // the value of x is converted into double, then the addition is performed. • We may use information in some widening conversions; int x = 1234567891; // int is 32 -bit and float is 32 -bit float y; y = x; // we will loose some precision (7 digit precision) 2022/1/2 COP 3330 Object Oriented Programming 65
/* Testing data conversion */ public class Data. Conv { public static void main(String [] args) { long i=100000001; // 9 digits float x; x=i; System. out. println("x="+x); } } Output: 2022/1/2 COP 3330 Object Oriented Programming 66
Java narrowing conversions byte 16 short char int long 32 float double char 16 byte, char byte, short, char, int 64 byte, short, char, int, long, float Can lose both numeric magnitude and precision Both short char and char are narrowing conversions! 2022/1/2 COP 3330 Object Oriented Programming short 67
• In Java, data conversions can occur in three ways: – assignment conversion – arithmetic promotion – casting • • Assignment conversion occurs when a value of one type is assigned to a variable of another Only widening conversions can happen via assignment int dollars; float money=25. 18; int=money; compile-time error 2022/1/2 COP 3330 Object Oriented Programming 68
• Arithmetic promotion happens automatically when operators in expressions convert their operands • When an integer and a floating-point number are used as operands to a single arithmetic operation, the result is floating point. The integer is implicitly converted to a floating-point number before the operation takes place. int i=37; double x=27. 475; System. out. println(“i+x=“+(i+x)); Output: i+x=64. 475 l 2022/1/2 COP 3330 Object Oriented Programming 69
Mixed-Type Arithmetic byte short int long float double Automatic (implicit) conversion: byte*long float*int float*double 2022/1/2 long*long float*float double*double COP 3330 Object Oriented Programming 70
Data Conversions • • 2022/1/2 Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total. COP 3330 Object Oriented Programming 71
Casting import java. io. *; class Test { public static void main(String args[]) { int a, b; a = 3; b = 2; System. out. println(a/b); System. out. println((float)(a/b)); System. out. println((float)a/b); System. out. println((float)a/(float)b); } } eola 16% javac Test. java eola 17% java Test 1 1. 0 1. 5 eola 18% 2022/1/2 COP 3330 Object Oriented Programming 72
int total=1, count=2; float result; result = (float) total / count; Output: result=0. 5 int total=1, count=2; float result; result = total / count; Output: 2022/1/2 result=0. 0 COP 3330 Object Oriented Programming 73
Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • Operators have a well-defined precedence which determines the order in which they are evaluated • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right • Parentheses can always be used to force the evaluation order 2022/1/2 COP 3330 Object Oriented Programming 74
Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4 a + b * c - d / e 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 2022/1/2 COP 3330 Object Oriented Programming 75
Assignment Revisited • The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated answer = 4 sum / 4 + MAX * lowest; 1 3 2 Then the result is stored in the variable on the left hand side 2022/1/2 COP 3330 Object Oriented Programming 76
Assignment Revisited • The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count = count + 1; Then the result is stored back into count (overwriting the original value) 2022/1/2 COP 3330 Object Oriented Programming 77
Increment and Decrement Operators i=k++; i=k; k=k+1; i=++k; k=k+1; i=k; i=k--; i=k; k=k-1; i=--k; k=k-1; i=k; int i, j, k=1; i=++k; j=k--; 2022/1/2 //initially i=j=0 // i=2, k=2 // j=2, k=1 COP 3330 Object Oriented Programming 78
Assignment Operators = += -= *= /= %= 2022/1/2 assignment addition, then assignment subtraction, then assignment multiplication, then assignment division, then assignment remainder, then assignment COP 3330 Object Oriented Programming 79
Comparison (or relational ) Operators Return type: boolean < > <= >= == != instanceof less than greater than less than or equal greater or equal not equal type comparison When == operator is used to compare two object variables of the same type, the result of comparison is true only if two variables refer to the same object. equals() method is used to compare objects. 2022/1/2 COP 3330 Object Oriented Programming 80
Numeric operators precedence 1. ( ) Parenthesis 2. ++ -Increment, Decrement 3. * / % Multiplication, Division, Modulus 4. + Addition, Subtraction 5. < > <= >= Relational Operatots 6. == != Equality Operators 7. = += -= *= /= %= Assignment Operators 2022/1/2 COP 3330 Object Oriented Programming 81
What value will j and k have after each of the following calculations? Assume j has the value 10 and k has the value 5 before each operation is done. k+=j; k-=j++; k*=++j*2; k/=25*j--; k%=j-3; 2022/1/2 COP 3330 Object Oriented Programming 82
Java Operators cont’d Evaluate the following expression: 9+6<=25*4+2 2 4 1 3 9+6<=25*4=2 2 3 1 4 int m=10, k=2, j=3; m*=++j+k--; j=4, k=1, m=60 j=j+1; m=m*(j+k); k=k-1; 2022/1/2 COP 3330 Object Oriented Programming 83
Increment and Decrement Operators • The increment operator ++ and the decrement operator -- can be applied to all integer and floating point types. • The increment and decrement operators are unary operators, and their arguments must be variables. • The increment operator adds one to its argument, the decrement operator subtracts one from its argument. • They can be prefix or postfix operators. – pre-increment, post-increment, pre-decrement, post-decrement – In pre-increment and pre-decrement operations, first these operations are performed then the value of the variable is used in the expression. – In post-increment and post-decrement operations, first the value of the variable is used in the expression, then these operations are performed. • Examples int y = y = 2022/1/2 x=2; ++x * x++ * x-- + --x + int y; 2; 3; 1; 1; x x is is 3, 4, 3, 2, y y is is 6 9 5 3 COP 3330 Object Oriented Programming 84
Operators and Precedence Rules Precedence Level 2022/1/2 Operator Operation Associates 1 ++ -- postfix increment, postfix decrement L to R 2 ++ -- + ~ ! pre-increment, post-increment, unary minus and plus bitwise complement logical not R to L 3 * / % multiplication, division, remainder L to R 4 + - addition, subtraction L to R 5 << >> >>> left shift, right shift with sign, left shift with zero L to R 6 < <= > >= less than, less than equal, greater than equal L to R 7 == != equal, not equal L to R 8 & bitwise and L to R 9 ^ xor L to R 10 | bitwise or L to R 11 && logical and L to R 12 || logical or L to R 13 ? : conditional operator R to L 14 = +=. . . assignment operators R to L COP 3330 Object Oriented Programming 85
Input and Output (in Console Applications) • Java I/O is based on input and output streams • There are pre-defined standard streams – System. in – System. out – System. err reading input writing output (for errors) keyboard monitor (Input. Stream object) (Print. Stream object) • print and println methods (defined in Print. Stream class) are used to write to the standard output stream (System. out). • We will get the inputs from the standard input stream (System. in). • To read character strings, we will create a more useful object of Buffered. Reader class from System. in. Buffered. Reader stdin = new Buffered. Reader(new Input. Stream. Reader(System. in)); 2022/1/2 COP 3330 Object Oriented Programming 86
String Class String(String str); //constructor char. At(int index); int compare. To(String str); String concat(String str); boolean equals. Ignore. Case(String str); int length(); String replace(char old. Char, char new. Char); String substring(int offset, int end. Index); String to. Lower. Case(); String to. Upper. Case(); 2022/1/2 COP 3330 Object Oriented Programming 87
s 1=new String(“Hello!”); s 2=new String(“Hello!”); s 1 Hello! s 2 Hello! boolean b 1=s 1==s 2; boolean b 2=s 1. equals(s 2) s 1=s 2; s 1 Hello! s 2 Hello! boolean b 3=s 1==s 2; 2022/1/2 COP 3330 Object Oriented Programming false true 88
Creating Objects • We use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object • Creating an object is called instantiation • An object (title ) is an instance of a particular class (String) 2022/1/2 COP 3330 Object Oriented Programming 89
Method invocation • 2022/1/2 Once an object has been instantiated, we can use the dot operator to invoke its methods title. length() COP 3330 Object Oriented Programming 90
Simple I/O Program // This program reads your name and print it together with "Hi" import java. io. *; public class Hi. Message { public static void main(String args[]) throws IOException { String your. Name; // Create a Buffered. Reader object Buffered. Reader stdin = new Buffered. Reader(new Input. Stream. Reader(System. in)); // print the prompt System. out. print("Enter your name and push enter key > "); System. out. flush(); // read the name your. Name = stdin. read. Line(); // print name together with Hi System. out. println("Hi " + your. Name); } } 2022/1/2 COP 3330 Object Oriented Programming 91
Numeric Input • We always read a string first, then we convert that string into a numeric value. String astring; int num; astring = stdin. read. Line(); num = Integer. parse. Int(astring); • parse. Int is a static method in the wrapper class Integer which converts a string into an int value (assuming that the string holds the digits of that integer). • If we put space before or after the integer number, the Java system will give an error message. 2022/1/2 COP 3330 Object Oriented Programming 92
Numeric Input – trim() • To able to put extra spaces before and after a numeric value during the input, we may use trim method of String class. num = Integer. parse. Int(astring. trim()); • trim method removes blanks in the front and the end of a string object (creates a new String object). String s; s = “ 123 “; s. trim() “ 123” 2022/1/2 COP 3330 Object Oriented Programming 93
To Read a double Value • We always read a string first, then we convert that string into a numeric value. String astring; double num; astring = stdin. read. Line(); num = Double. parse. Double(astring); • parse. Double is a static method in the wrapper class Double which converts a string into an double value (assuming that the string holds the digits of that double number). • To remove extra spaces before and after a numeric value during the input, we may use trim method of String class. num = Double. parse. Double(astring. trim()); 2022/1/2 COP 3330 Object Oriented Programming 94
String argv[] • Useful to pass parameters into program • • • public static void main(String argv[]) use argv. length to see how many parameters were entered argv[0] gives first parameter (string) argv[1] gives second string String s 1 = argv[0]; 2022/1/2 COP 3330 Object Oriented Programming 95
Simple I/O in Applets import java. awt. *; import java. applet. *; import java. awt. event. *; public class Hi. Message. Applet extends Applet implements Action. Listener { Label prompt, greeting; // Output areas Text. Field input; // Input area // This method will be called when the applet starts, // and creates the required parts of the applet. public void init() { // Create prompt area and put it into the applet prompt = new Label("Enter your name and push return key: "); add(prompt); // Create input area and put it into the applet input = new Text. Field(20); add(input); // Create greeting area and put it into the applet greeting = new Label(""); add(greeting); // "this" (this applet) will listen the input area and // respond the events in this area. input. add. Action. Listener(this); } 2022/1/2 COP 3330 Object Oriented Programming 96
Simple I/O in Applets (cont. ) // This method will be called when anytime a string is typed // in input area and the return key is pushed. public void action. Performed(Action. Event e) { greeting. set. Size(300, 20); greeting. set. Text("Hi " + input. get. Text()); input. set. Text(""); } } 2022/1/2 COP 3330 Object Oriented Programming 97
Simple I/O in Applets (Output) At the beginning Before we push the return key After we pushed the return key 2022/1/2 COP 3330 Object Oriented Programming 98
Simple I/O in Applets (Output-cont. ) Before we push the return key After we pushed the return key 2022/1/2 COP 3330 Object Oriented Programming 99
Another Applet with I/O Operations import public java. applet. Applet; java. awt. *; java. awt. event. *; class Sum. Average. Applet extends Applet implements Action. Listener { Label prompt; Text. Field input; int number; int sum; int count; double average; // // // prompt area input area for positive integer value of positive integer sum of all numbers number of positive integers average of all numbers // Create the graphical components and initialize the variables public void init() { // Create prompt and put it into the applet prompt = new Label( "Enter a positive integer and push the return key: " ); add(prompt); // Create input area and put it into the applet input = new Text. Field(10); add(input); // Initialize the variables sum = 0; count = 0; // this applet will listen input area and respond to the events hapenning in this area input. add. Action. Listener(this ); } 2022/1/2 COP 3330 Object Oriented Programming 100
Another Applet with I/O Operations (cont. ) // Respond to the events in input area public void action. Performed(Action. Event e) { // Get the input and convert it into a number = Integer. parse. Int(e. get. Action. Command(). trim ()); // Evaluate the new values sum = sum + number; count = count + 1; average = (double) sum / count; input. set. Text(""); // show the results repaint(); } // Show the results public void paint(Graphics g. draw. String("SUM : " + g. draw. String("AVG : " + g. draw. String("COUNT : " } g) { Integer. to. String(sum), 50); Double. to. String(average), 50, 70); + Integer. to. String(count), 50, 90); } 2022/1/2 COP 3330 Object Oriented Programming 101
Another Applet with I/O Operations (output) 2022/1/2 COP 3330 Object Oriented Programming 102
What happens when we type a real number? 2022/1/2 COP 3330 Object Oriented Programming 103
Logical (Boolean) Operators ! & ^ | && || Examples Unary logical compliment (NOT) Evaluation AND boolean XOR Evaluation OR Short-circuit AND Short-circuit OR if is. High. Presure is true, the second operand will not be evaluated if(!is. High. Pressure&&(temp 1>temp 2)){…} boolean b 1=(x<y)||(a>b++); boolean b 2=(10<5)&(5>1); both operands will always be evaluated 2022/1/2 COP 3330 Object Oriented Programming 104
The Random Class (java. util) see page 727 Methods: Random() class constructor float next. Float() returns a random float number between 0. 0 and 1. 0 int next. Int() returns a random integer number between -231 and 231 -1 2022/1/2 COP 3330 Object Oriented Programming 105
Example import java. util. Random; an object of class Random is created (instantiated) public class Random. Numbers { Random generator=new Random(); int num 1; float num 2; num 1=generator. next. Integer(); num 2=generator. next. Float(); …. } Methods from class Random are called 2022/1/2 COP 3330 Object Oriented Programming 106
Math Class (java. lang) see page 710 Methods: static int abs(int num) static double acos(double num) static double asin(double num) static double cos(double angle) static double exp(double num) static double pow(double num, int power) static double sqrt(double num) Methods that can be invoked through the class name (without having to instantiate an object first) are called static (or class) methods 2022/1/2 COP 3330 Object Oriented Programming 107
import java. util. Random; public class Random. Numbers { public static void main (String[] args) { Random generator = new Random(); int num 1; float num 2; num 1 = generator. next. Int(); num 1 = Math. abs (generator. next. Int()) % 10; the method abs(int) from class Math is called without instantiation of an object (via class name) num 1 now is an integer from 0 to 9. 2022/1/2 COP 3330 Object Oriented Programming 108
cont’d num 1 = Math. abs (generator. next. Int()) % 10 + 1; System. out. println ("1 to 10: " + num 1); num 1 = Math. abs (generator. next. Int()) % 20 + 10; System. out. println ("10 to 29: " + num 1); num 2 = generator. next. Float(); System. out. println ("A random float: "+num 2); num 2 = generator. next. Float() * 6; num 1 = (int) num 2 + 1; System. out. println ("1 to 6: " + num 1); 2022/1/2 COP 3330 Object Oriented Programming 109
println(…) is a method declared in the class Print. Stream. java. io. Print. Stream class is Java’s printing expert: public class { … public … } Print. Stream extends Filter. Output. Stream print (String s) { … } print (int i) {…} print (boolesn b) {…} println (String s) { … } So, different print() and println( ) methods belong to Print. Stream class 2022/1/2 COP 3330 Object Oriented Programming 110
System. out is a variable from class System and is of type Print. Stream public final class System {. . . public static Print. Stream out; // Standart output stream public static Print. Stream err; // Standart error stream public static Input. Stream in; // Standart input stream. . . } System class is part of java. lang package. 2022/1/2 COP 3330 Object Oriented Programming 111
System. out. println(“Hello World!”) object method Information provided to the method (parameters) • A method println(. . . ) is a service that the System. out object can perform. This is the object of type Print. Stream, declared in java. lang. System class. • Method println(. . . ) is invoked ( or called ) • The method println(…) is called by sending the message to the System. out object, requesting the service. 2022/1/2 COP 3330 Object Oriented Programming 112
Number. Format Class (java. text) page 720 This class is abstract that means that an object can not be instantiated using a new operator. You request an object from one of the methods invoked through class itself String format(double number) returns a string containing the number in the format specified by the object converts double_n into string in accordance with obj. Number. Format Example: String s=obj. Number. Format. format(double_n); an instance of Number. Format object 2022/1/2 COP 3330 Object Oriented Programming 113
Methods of Number. Format class that return an object static Number. Format get. Currency. Instance() returns an instance of Number. Format object, that represents currency format static Number. Format get. Percent. Instance() returns an instance of Number. Format object, that represents percentage format 2022/1/2 COP 3330 Object Oriented Programming 114
Example import java. text. Number. Format; public class Price { double total=19. 35; double tax_rate=0. 06; Number. Format money= Number. Format. get. Currency. Instance(); String formated_total= money. format(total); Number. Format percent= Number. Format. get. Percent. Instance(); String formated_tax=percent. format(tax_rate); } 2022/1/2 COP 3330 Object Oriented Programming 115
Decimal. Format Class (java. txt) Decimal. Format (String pattern) constructor: creates a Decimal. Format object with specified pattern argument of String type is sent to constructor name of object Decimal. Format fmt=new Decimal. Format(“ 0. ###”); type of object 2022/1/2 an object is created constructor is called COP 3330 Object Oriented Programming 116
void apply. Pattern (String pattern) applies the specified pattern to the Decimal. Format object fmt. apply. Pattern(“ 0. ####”); 2022/1/2 COP 3330 Object Oriented Programming 117
String format (double number) returns a string containing the number, formated in accordance with the Number. Format object int radius=5; double area=Math. PI*Math. pow(radius, 2); System. out. println(fmt. format(area)); Output: 78. 5398 2022/1/2 COP 3330 Object Oriented Programming 118
- Slides: 118