Java Data types and input/output Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email: sharma@cse.uta.edu Course Url: https://wweb.uta.edu/faculty/sharmac/courses/coursepage.asp URL: http://itlab.uta.edu/sharma Project 1 I want to make sure you understand project 1 and are making progress Are you able to figure out the algorithms for the methods to be implemented! Any questions? Make sure you test the code thoroughly (both yours and what we have provided) Make sure the output is clear, easy to understand, and can be used to check for correctness This will help you get a firm grip over java basics 2 Primitive data types in Java Data type size range byte 1 byte -128 to +127 short 2 bytes -32768 to +32767 int 4 bytes single precision long 8 bytes double float 4 bytes single double 8 bytes double //is default in Java Java is a strongly typed language float real; real = 34.33 //error, all floating point literals are considered double; declare real as double Primitive data types (2) Data type size range boolean 1 byte true or false char 2 byte any char (uses unicode) These data types are called primitive because you cannot create objects of this type. Objects have attributes and methods. With primitive data types, you can only create variables and a variable can hold a single value. Note that strings are not primitive in Java Implemented as a class (i.e., is an object) All floating point computations follow the IEEE 754 specification 1
Java Classes for primitive types Java does not allow you to store primitive types in some objects (e.g., ArrayList) Hence, if you want to store numbers, they have to be objects Java provides an object equivalent for all primitive types These are objects and hence can be stored in other objects The following object classes are provided by Java Integer //to store an integer Long Double Float Char Boolean See more on boxing and auto boxing Java Data Types There are 3 special floating point values to denote overflows and errors Positive infinity (Double.POSITIVE_INFINITY) Negative infinity (Double.NEGATIVE_INFINITY) NaN (not a number) (Double.NaN) If (x == NaN) // is never true All NaN values are considered distinct Use (Double.isNaN(x) //check whether x is NaN 5 6 Java Big Numbers If the precision of basic integer and floating point is not sufficient, there are classes in the java.math.package to help you BigInteger and BigDecimal classes manipulate numbers with arbitrarily long sequence of digits As they are not primitive types, you cannot use + and. Need to use methods of the class for manipulation BigInteger bi, ci = BigInteger.valueOf(200); BigInteger di = bi.add(ci); Notes on C and C++ In C and C++, int denotes an integer type that depends on the target machine 2 bytes on 16 bit processors and 4 bytes on 32 bit processors In Java, the size of all numeric types are platform independent Java has tried its best to be platform and OS independent! Look up javadoc BigInteger for more information 7 8 2
Basic Input/output in Java Input and outputs in Java are considered streams System.in is the object used for console input Need to import some classes (e.g., Scanner) Create an object of that class Use methods of that class to perform input/output Once you have the input, you can perform error checks 9 More about input/output We have seen how to output strings and numbers using Syste.out.println, print, and printf methods In Java, every class is expected to have a method to convert its attributes into a printable ascii form (tostring() method) The equivalent of this method is supplied by Java for primitive type and some non primitive types (e.g., String) So, you can write System.out.printf("%5d%10s", i, ", "); to output an integer i using a format However, doing input is a little more involved as you need to create objects that accept input from the keyboard (remember you can also read from a file which we will do later) 10 Input Create an object of type Scanner using Scanner input = new Scanner(System.in); Note that you have to add import java.util.scanner //at the top of the file Code fragment for accepting input and error checking // prompt for input, read, and validate do { System.out.print( "Enter lower number >= " + lowestvalue + ": "); lownum = input.nextint(); if (lownum < lowestvalue) System.out.println("input value: " + lownum + " is less than " + lowestvalue); } while (lownum < lowestvalue); Enter lower number >= 10: 19 //is ok Enter lower number >= 10: 5 //is not ok; will ask again 11 3
What happens if you type 45.23 instead of 45? or Type hello instead of 45? An InputMismatchException occurs when Scanner method nextint receives a String that does not represent a valid integer. More on input/output We will be using nextint() and oters for project 2 Similarly, there are methods of Scanner class for next() // returns next token as a String nextdouble() nextboolean() nextfloat() nextchar() nextlong() hasnext() // returns boolean hasnextline() //returns whether there is a line //terminator in the input nextline() More about input/output (2) Be careful when using the method nextline() Note that when you perform an enter from the keyboard, a newline char is inserted into the buffer nextint() and all other nextxyz() methods are designed to skip the nextline character that is sitting in the buffer. However, the nextline() method reads the nextline char and takes it as input! You will have to use an extra nextline() call to skip over the newline character sitting in the buffer! See page 80 in the text book (8 th ed) 4
Reading from a file Many a times, it is easier to read from a file rather than command prompt Avoids typing while debugging, and mistakes Create a FileReader object Use that to create a BufferedReader Object import java.io.*; FileReader freader = new FileReader( customers.txt ); BufferedReader inputfile = new BufferedReader(freader); can use inputfile.readline() to read a line of input (not including the newline character) into a String if the value of the string read is null, then it is end of file can use inputfile.close() for closing the file throws IOException Reading data from a file Some methods of BufferedReader class int read() //reads a single character and returns its Unicode value Int read(char[] array) //returns number of characters int read(char[] array, int offset, int length) // stores from offset, length chars String readline() close() long skip(long n) //skip n characters in the stream 18 Writing to a file Many a times, it is easier to write to a file rather than command prompt (or both) Allows checking results easily (if long) Create a FileStream object (using FileWriter class) Use that to create a PrintWriter Object Allows print, println, and printf methods import java.io.*; FileStream fstream = new FileWriter( customers.txt ); PrintWriter outputfile = new PrintWriter(fstream); can use outputfile.println( joe ) to write an arbitrary string outputfile.println(82) outputfile.print(name + + idnumber) can use outputfile.close() for closing the file throws IOException Importing classes import declaration Helps the compiler locate a class that is used in this program. Rich set of predefined classes that you can reuse rather than reinventing the wheel. Classes are grouped into packages named groups of related classes and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API). You use import declarations to identify the predefined classes used in a Java program. 5
System is a class. Importing classes Part of package java.lang. Class System is not imported with an import declaration at the beginning of the program. By defauly, Java,lang is automatically imported into every java program. Usually, when your program accepts an input from command prompt, it is customary to prompt with appropriate details Packages Packages Set of predefined classes in Java Related classes are grouped into packages Group of all packages known as Java class library or Java applications programming interface (Java API) JOptionPane is in the javax.swing package This package has classes for using Graphical User Interfaces (GUIs) Packages are declared at the beginning of the file package edu.uta.carddeck; 2.7 Arithmetic (Cont.) Rules of operator precedence Multiplication, division and remainder operations are applied first. If an expression contains several such operations, they are applied from left to right. Multiplication, division and remainder operators have the same level of precedence. Addition and subtraction operations are applied next. If an expression contains several such operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence. When we say that operators are applied from left to right, we are referring to their associativity. Some operators associate from right to left. Complete precedence chart is included in Appendix A. 6
2.8 Decision Making: Equality and Relational Operators Condition An expression that can be true or false. if selection statement Allows a program to make a decision based on a condition s value. Equality operators (== and!=) Relational operators (>, <, >= and <=) Both equality operators have the same level of precedence, which is lower than that of the relational operators. The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right. Thank You! 28 7