Title: Basic Data Types
1Basic Java
- Basic Data Types
- Strings
- Arrays
- Control Structures
- Methods
2Basic Java Data Types
- Numeric Data Types and Arithmetic
- Boolean Type
- String Type
- Array Type
3Primitive Data Types
4Numeric Data Types
- Ranges of numeric types are the same for all
hardware platforms. - Arithmetic, relational, and boolean operators are
the same as those in C. - Automatic type conversion is possible for
- byte?short ?int ?long ?float ?double
- char ?int
- Numeric constants are declared with keyword
final.
5Hello World
- public class Helloworld
- public static void main(String args)
- System.out.println("Hello World!")
-
-
- System.out class
- method println()
- public to all
6Sample Program
public class BasicJava1 public static void
main(String args) int i,
j100 //System.out.println(i) //error i50
System.out.println(ij) System.out.println(i
" "j) //what? j i //much like
C final float PI 3.14162F //const //short
s j //error
7char and boolean
- char type is pretty much the same as Cs.
- Relational and boolean operators are the same,
too. - The new boolean type in Java has the literal
values, true and false. - boolean types cannot be converted, implicitly or
explicity, to/from other types. - Example boolean b (boolean) j
- Example int j (int) b
8Special Characters
- Backspace \b
- Tab \t
- Linefeed \n
- Carriage return \r
- Double quote \
- Single quote \
- Backslash \\
9Math class
- Math. is a collection of mathematical functions
abs(x), ceil(x), cos(x), exp(x), floor(x),
log(x), max(x,y), min(x,y), pow(x,y), sin(x),
sqrt(x), tan(x).
public class BasicJava2 public static void
main(String args) System.out.println(Math.s
qrt(9)) float x 10.0f //10.0 is a
double System.out.println(Math.pow(x, 2))
10Basic I/O with Swing
import javax.swing. //import javax.swing.JOption
Pane public class BasicJava3 public
static void main(String args)
double x0, y0 String input
input JOptionPane.showInputDialog("Power
Function Demo\nEnter the base") x
Double.parseDouble(input) input
JOptionPane.showInputDialog("Power Function
Demo\nEnter the exponent") y
Double.parseDouble(input)
System.out.println(x " raised to the power of
" y " is equal to
" Math.pow(x,y)) JOptionPane.showMessa
geDialog( null, x "
raised to the power of " y " is equal to "
Math.pow(x,y), "Results Window",
//JOptionPane.WARNING_MESSAGE)
//JOptionPane.PLAIN_MESSAGE)
JOptionPane.INFORMATION_MESSAGE)
11String Type
- String is a predefined class in Java.
- It is not a char array.
- .length() returns length
- .substring(a,b) returns a substring
- .equals(String) is a boolean function
- .compareTo(String) is similar to strcmp()
- is the concatenation operator
- also is a concatenation operator for string
- .toLowerCase(), toUpperCase(),
12String Declaration and Anonymous Strings
- Since String is a class, a declaration is a call
to its constructor String s. - Java treats ABC as a String literal or an
anonymous String object, thus, the following
declaration is a copy constructor call with ABC
as the initial value - String s new String(ABC)
- s is a String object not a char array, thus, sj
does not work. - operator does not work because String names
(internal hexcode IDs) will be compared directly.
13Example
- A String, just like any object, can be referenced
via a name (identifier). - A new String object can be created with new.
- public class BasicJava4
-
- public static void main(String args)
-
- String s new String("Hello") //s is an
identifier - String t new String("Hello") //copy
constructor call - if (s t) System.out.println("Match!")
- if (s.equals(t)) System.out.println("OK")
- //How about String r new String(t) ?
-
14Assignment Operator
- Caution Assignment operator for primitive object
means copy however, for objects, it is an
assignment of references (names). - Strings are immutable objects-they cant be
changed but they can be shared. - Un-referenced objects are garbage, which will be
collected automatically.
public class StrAssignment public static
void main(String args) String r
String s new String("Hello") String t
new String("Hello") r s t
t new String("World")
System.out.println(r) System.out.println(
s) System.out.println(t) //how
many Strings are there now?
15More Ways to Initialize Strings
- char a 'H','e','l','l','o' //a simple
char array - String s new String(a)
- //it's also a way to "cast" a char array to a
String! - String t "Hello" //copy constructor call?
- In Suns docs, it said the following
- String str "abc"
-
- is equivalent to
- char data 'a', 'b', 'c'
- String str new String(data)
- Really?
16All Objects are Dynamically Allocated
- So we have three ways to assign values to a
String. - String s new String(ABC)
- String s new String(cArray)
//cArray is a char - String s ABC
- s ABC //assignment statement
- The last two methods are actually identical!
17Example
- public class BasicJava6
-
- public static void main(String args)
-
- char a 'H','e','l','l','o' //a simple
char array -
- String s new String("Hello") //copy
constructor - String t new String(a) //constructor
- String u "Hello" //Assignment? Probably
- String v
- v "Hello" //Assignment
- if (uv) System.out.println(A Match!")
- if (st) System.out.println("Goodness")
- if (su) System.out.println("No Way")
- if (sv) System.out.println("I better go to
sleep") -
18Console I/O
import java.util. public class InputTest
public static void main(String args)
Scanner in new Scanner(System.in) //
get first input System.out.print("What is
your name? ") String name
in.nextLine() // get second input
System.out.print("How old are you? ") int
age in.nextInt() // display output on
console System.out.println("Hello, " name
". Next year, you'll be " (age 1))
19Array Types
- Arrays in Java are similar to dynamic arrays in
C. - Arrays are first class objects in Java that come
with a number of predefined methods in
java.util.Arrays - static void arraycopy(...)
- static void equals(Xxx a, Object rhs)
- static void sort(Xxx a)
- Watch out for assignment operators.
20Example
- import java.util.
- public class BasicJava7
-
- public static void main(String args)
-
- int a 5, 4, 3, 2, 1
- int b new int 10
- for (int i0 ilt10 i)
- bi 10
-
- b a //not copying
- System.arraycopy(a, 0, b, 4, 5)
-
-
- Arrays.sort(a)
- for (int i0 ilt5 i)
- System.out.println(ai)
-
21Example LotteryDrawing
import java.util. import javax.swing. public
class LotteryDrawing public static void
main(String args) String input
JOptionPane.showInputDialog ("How many
numbers do you need to draw?") int k
Integer.parseInt(input) input
JOptionPane.showInputDialog ("What is
the highest number you can draw?") int n
Integer.parseInt(input) // fill an array
with numbers 1 2 3 . . . n int numbers
new intn for (int i 0 i lt
numbers.length i) numbersi i
1 // draw k numbers and put them into a
second array int result new intk
for (int i 0 i lt result.length i)
// make a random index between 0 and n - 1
int r (int)(Math.random() n) //
pick the element at the random location
resulti numbersr // move the
last element into the random location
numbersr numbersn - 1 n--
22Example LotteryDrawing (cont.)
// print the sorted array
Arrays.sort(result) System.out.println
("Bet the following combination. It'll make
you rich!") for (int i 0 i lt
result.length i) System.out.println(re
sulti) System.exit(0)
- More methods can be defined with a class.
- Parameter passing is pass-by value (copy).
- When an actual parameter is evaluated
- A primitive variable's data value is passed in
(by-value in C). - An object's reference is passed in since an
object's id is really a reference to that object
(by-reference in C). - Thus, array is passed by reference.
23Example Retirement
import javax.swing. public class Retirement
public static void main(String args) //
read inputs String input
JOptionPane.showInputDialog ("How much
money do you need to retire?") double goal
Double.parseDouble(input) input
JOptionPane.showInputDialog ("How much
money will you contribute every year?")
double payment Double.parseDouble(input)
input JOptionPane.showInputDialog("Interest
rate in ") double interestRate
Double.parseDouble(input) double balance
0 int years 0 // update account
balance while goal isn't reached while
(balance lt goal) // add this year's
payment and interest balance
payment double interest balance
interestRate / 100 balance
interest years
System.out.println("Your can retire in " years
" years.") System.exit(0)
24Formatting Ouput
- Using NumberFormat class in java.text package.
- Numbers 3,333.333
- Currency 3,333.33
- Percentage 333,333
- Example
- double x 10000 / 3.0
- NumberFormat formatter getNumberInstance()
- String s formatter.format(x)
- formatter.setMaximumFractionDigits(2)
- System.out.println(s)
25Example Retirement2
import java.text. import javax.swing. public
class Retirement2 public static void
main(String args) String input
JOptionPane.showInputDialog ("How much
money will you contribute every year?")
double payment Double.parseDouble(input)
input JOptionPane.showInputDialog("Interest
rate in ") double interestRate
Double.parseDouble(input) double balance
0 int year 0 NumberFormat
formatter NumberFormat.getCurrencyInstance()
// update account balance while user isn't
ready to retire do // add this
year's payment and interest balance
payment double interest balance
interestRate / 100 balance
interest year // print
current balance System.out.println("After
year " year ", your balance is "
formatter.format(balance)) // ask if
ready to retire and get input input
JOptionPane.showInputDialog("Ready to retire?
(Y/N)") input input.toUpperCase()
while (input.equals("N"))
System.exit(0)
26Discussion
- What about returning a local array to the caller?
Isnt that a big no no in C? - What about the return type? Is it by value? Or
by reference? - Do all functions have to be public?
- What about non-public functions?
- Two Dimensional arrays is more or less similar to
Cs dynamic 2D arrays.