COMP201 Java Programming

Topic 2: Java Basics

COMP201 Topic 2 / Slide 2

Objective and Outline 

Objective 



Show basic programming concepts

Outline  

What do java programs look like? Basic ingredients – Java primitive types – Variables and constants – Operators and control flow



Simple commonly used built-ins. – Simple input/output – Arrays and Strings

COMP201 Topic 2 / Slide 3

What do java program look like? public class MyProgram { public static void main(String args[]) { System.out.println(“Hello world!”); } } //File: MyProgram.java 

public: Access modifier

class: everything is inside a class  MyProgram: class name. 



matches file name.



Case sensitive

main: method of the wrapping class 



Compilation and run: javac MyProgram.java => MyProgram.class java MyProgram

COMP201 Topic 2 / Slide 4

Objective and Outline 

Outline  

What do java programs look like? Basic ingredients – Java primitive types – Variables and constants – Operators and control flow



Simple commonly used built-ins. – Simple input/output – Arrays and Strings

COMP201 Topic 2 / Slide 5

Basic Ingredients/Primitive Types 



  

Integers  byte (1 byte, -128 to 127)  short (2 bytes) For really large numbers use  int (4 bytes) BigInteger and BigDecimal  long (8 bytes) classes Floating-point types  float (4 bytes, 6-7 significant decimal digits)  double (8 bytes, 15 significant decimal digits) char (2 byte, Unicode) (ASCII 1 byte) boolean (true or false) Those are all the primitive types in Java. Everything else is an object.

COMP201 Topic 2 / Slide 6

Basic Ingredients/Primitive Types 

Legal conversions between numeric types char bytes

short

int

float 



double

Arrows indicate direction of legal and automatic conversion – double x = 123; – long x = 123456789; float y = x;



long

Solid arrow: no loss of precision Dotted arrow: might lose precision – z=1.234567E8

COMP201 Topic 2 / Slide 7

Basic Ingredients/Primitive Types char bytes

short

int

float 

double

Conversion in the opposite direction required explicit cast.  





long

double x = 9.997; int num = (int) x; int num = x; // does not compile

Can easily lead to the loss of precision (round-up errors) Cannot convert between boolean and numerical values.

COMP201 Topic 2 / Slide 8

Objective and Outline 

Outline  

What do java programs look like? Basic ingredients – Java primitive types – Variables and constants – Operators and control flow



Simple commonly used built-ins. – Simple input/output – Arrays and Strings

COMP201 Topic 2 / Slide 9

Basic Ingredients/Variables and Constants 

Variables can be declared anywhere for (int i = 0; i < 20; i++) { System.out.println(“Hi”); char ch = ‘A’; } double pi = 3.14159;



Java compilers require initialization of local variables before use public void someMethod() { … int x; // does not compile System.out.println(“The value of x is “ + x); }



Instance variables of class automatically initialized.

COMP201 Topic 2 / Slide 10

Basic Ingredients/Variables and Constants 

final marks a variable “read-only”  Variable is assigned once and cannot be changed public void someMethod() { final double pi

=

3.14159;

.. .. ..

pi = 3.14; // illegal

} 

Use static final to define constants which are available to multiple objects of the same class public class Time { static final int MinHour = 0; static final int MaxHour = 23; private int hour, minute; // these properties are set to 0 // unless overwritten by constructor … }

COMP201 Topic 2 / Slide 11

Objective and Outline 

Outline  

What do java programs look like? Basic ingredients – Java primitive types – Variables and constants – Operators and control flow



Simple commonly used built-ins. – Simple input/output – Arrays and Strings

COMP201 Topic 2 / Slide 12

Basic Ingredients/Operators 

Basically the same as C++: +, -, *, /, %, ++, --, <, <=, >, >=, ==, !=, !, &&, || =, +=, -=, *=, /=, %=,



User cannot “overload” operators; although + is overloaded to do string concatenation 

In C++: – Int x=0; x += 1; – String& String::operator+=( const String &s)..



Note that methods can be overloaded

COMP201 Topic 2 / Slide 13

Basic Ingredients /Operators No Pointers! 

No explicit pointer types (although objects are implemented as references)



No & or * operators 

In C++:   

 

int *i = (int *) malloc( 3 * sizeof(int)); *(i+1) = 2; int& y = i;

No pointer arithmetic No function pointers

COMP201 Topic 2 / Slide 14

Basic Ingredients/Control flow Basically the same as C++: if (boolean-expr) statement; (has optional else) if ( x = 0 ) //leads to compiling error

for (expr; boolean-expr; expr) statement; while (boolean-expr) statement; (do-while variant also) switch (integer-expr) case constant: statement; break;

COMP201 Topic 2 / Slide 15

Basic Ingredients/Control flow Recursion Basically the same as C++: public class Factorial { public static int factorial( int n ) { if ( n <=1 ) return 1; return factorial( n-1 ) * n; } public static void main(String args[]) { System.out.println( factorial ( 4 ) ); } }//Factorial.java

COMP201 Topic 2 / Slide 16

Objective and Outline 

Outline  

What do java programs look like? Basic ingredients – Java primitive types – Variables and constants – Operators and control flow



Simple commonly used built-ins. – Simple input/output – Arrays and Strings

COMP201 Topic 2 / Slide 17

Simple Input/Output 

Contents   



Writing to standard output Reading keyboard input via dialog box Formatting output

We discuss I/O in more detail later.

COMP201 Topic 2 / Slide 18

Simple Input/Output 

It is easy to print output to the “standard output device (the console window) by using the predefined Stream objects out

System.out.print(“Your name is “ + name + “ and you are “ + num + “ years old.”);

COMP201 Topic 2 / Slide 19

Simple Input/Output 

It is a bit more complex to read input from the “standard input device” using Stream.



However it is easy to supply a dialog box for keyboard input: JOptionPane.showInputDialog(promptString) The return value is the string that the user typed

COMP201 Topic 2 / Slide 20

Simple Input/Output 

Need to include this statement: import javax.swing.*; //JOptionPane class is defined in that package







For example: you can query name of the user by: String name= JOptionPane.showInputDialog(“Your name:”); To read in a number, use the Integer.parseInt or Double.parseDouble method to convert the string to its numeric value. For example, String input= JOptionPane.showInputDialog(“Your age:”); int age = Integer.parseInt(input); End the program with the method call: System.exit(0);

COMP201 Topic 2 / Slide 21

Objective and Outline 

Outline  

What do java programs look like? Basic ingredients – Java primitive types – Variables and constants – Operators and control flow



Simple commonly used built-ins. – Simple input/output – Arrays and Strings

COMP201 Topic 2 / Slide 22

Arrays 

Contents   

Arrays are objects Arrays are implemented as references Multidimensional arrays

COMP201 Topic 2 / Slide 23

Arrays  

Arrays are objects of class java.lang.reflect.Array Can’t specify size when declaring array int arr[3]; int arr[]; int[] arr;

  

 

// not legal in Java! // okay // okay (same as previous line)

Arrays (as all objects) are dynamically allocated int[] arr = new int[3]; Before allocation, array variable is null All elements are zeroed when array allocated Destroyed automatically by garbage collector. No delete operator Shorthand to declare, allocate, and initialize int[] arr = { 5, 10, 15, 20};

COMP201 Topic 2 / Slide 24

Arrays 

Java array (object) always knows its own length int[] arr = {5, 20, 15, 10}; System.out.println(“Length is ” + arr.length);



Elements indexed from 0 to length-1, like C++



Raises exception for “ArrayIndexOutOfBounds”



Length is fixed when allocated; create new array and copy over to change length

COMP201 Topic 2 / Slide 25

Arrays 

Used in similar way as ordinary arrays int sum(int[] arr) { int i, sum = 0; for (i=0; i < arr.length; i++) sum += arr[i]; return sum; }

COMP201 Topic 2 / Slide 26

Arrays are references 

Arrays are objects, hence, are implemented as references (reference is a pointer in disguise) int[] arr = {5, 20, 15, 10}; int[] b = arr; b[0] = 3; // arr[0] also becomes 3!



Array copying (java.lang.System) System.arraycopy(from, fromIndex, to, toindex, count); int[] c; System.arraycopy(arr, 0, c, 0, 4);



Array sorting (java.util.Arrays) Arrays.sort(arr)

//use a tuned QuickSort

COMP201 Topic 2 / Slide 27

Array Examples public class ArrayRef { public static void main( String[] args ) { int [] a = {0, 1, 2, 3, 4}; int [] b = {10, 11, 12, 13, 14}; a = b; b = new int[] { 20, 21, 22, 23, 24 }; for (int i=0; i
public class Swapping { public static void main(String argv[]) { int[] a = {1,2,3}; for (int i=0; i<3; i++) System.out.print(a[i]+" "); System.out.print(“\n”); swap(a,0,2); for (int i=0; i<3; i++) System.out.print(a[i]+" "); System.out.print(“\n”); } public static void swap(int[] a, int i, int j) { int temp = a[j]; a[j]=a[i]; a[i]=temp; } } //Swapping.java

COMP201 Topic 2 / Slide 29

Multidimensional Arrays int[][] matrix = new int[5][10]; int[] firstRow = matrix[0]; //ref to 1st row int[] secondRow = matrix[1]; //ref to 2nd row int firstElem = matrix[0][0]; firstElem = firstRow[0];

COMP201 Topic 2 / Slide 30

Strings 

Contents 

Strings are objects, immutable, differ from arrays  Basic methods on Strings  Convert String representation of numbers into numbers  StringBuffer, mutable version of Strings

COMP201 Topic 2 / Slide 31

String    

Java.lang.String Java.lang.StringBuffer String is an object Creating a String 

form string literal between double quotes String s = “Hello, World!”;



by using the new keyword String s = new String(“Java”);

COMP201 Topic 2 / Slide 32

Accessor Methods 

String.length() 



obtain the length of the string

String.charAt(int n) 

obtain the character at the nth position

COMP201 Topic 2 / Slide 33

Strings 

String is a class (java.lang.String)offering methods for almost anything String s = “a string literal”;



+ is concatenation, when you concatenate a string with a value that is not a string, the latter is converted to a string s = “The year is ” + 2002 + “!”;



Everything can be converted to a string representation including primitive types and objects (topic 3, class object)

COMP201 Topic 2 / Slide 34

Strings 

A String is not an array. It is immutable. You cannot change a String 

but you can change the contents of a String variable and make it refer to a different String.

String s = “Hello”; s[2]=‘a’; // Illegal s = “Bye”; //Legal 

Equality test: s.equals(t) // determines whether s and t are same s == t// determines whether s and t stored at same location

COMP201 Topic 2 / Slide 35

String Example public class StringExample { public static void main(String argv[]) { String h = “hello”; String w = “world”; System.out.println(h + “ “ +w); w = h.substring(1,3); w += "binky"; for (int i = 0; i < w.length(); i++) System.out.println(w.charAt(i)); int pos = w.indexOf("in"); System.out.println("Starting position of \"in\ " in string \" " + w + " \" is " + pos);

COMP201 Topic 2 / Slide 36

String Example if ( h=="hello" ) System.out.println( "String h == \"hello\" "); if ( "hello".equals(h) ) System.out.println("\"hello\" == string h "); } } } //StringExample.java

COMP201 Topic 2 / Slide 37

Example - String 

To print a string in reverse order

class ReverseString { public static void reverseIt(String source) { int i, len = source.length(); for (i = (len - 1); i >= 0; i--) { System.out.print(source.charAt(i)); } } }

COMP201 Topic 2 / Slide 38

Convert String to number 

String class itself does not provide such a



conversion Type wrapper classes (Integer, Double, Float and Long) provide a method valueOf to do the job String piStr = “3.14159”; Float pi = Float.valueOf(piStr);

COMP201 Topic 2 / Slide 39

StringBuffer    

The String class is used for constant strings While StringBuffer is for strings that can change StringBuffer contains a method tostring() which returns the string value being held Since String is immutable, it is “cheaper”!

COMP201 Topic 2 / Slide 40

StringBuffer class ReverseString { public static String reverseIt(String source) { int i, len = source.length(); StringBuffer dest = new StringBuffer(len);

for (i = (len - 1); i >= 0; i--) { dest.append(source.charAt(i)); } return dest.toString(); } }

COMP201 Topic 2 / Slide 41

StringBuffer 

StringBuffer(int length) 



 

leaving the length undetermined is less efficient

length, charAt, capacity append, insert, substring toString

COMP201 Topic 2 / Slide 42

StringBuffer StringBuffer sb = new StringBuffer("Drink Java!"); StringBuffer prev_sb = sb; sb.insert(6, "Hot "); sb.append(" Cheer!"); System.out.println(sb.toString() + " : " + sb.capacity()); System.out.println("prev_sb becomes " + prev_sb ); **** output ***** Drink Hot Java! Cheer! : 27 (initial size + 16) prev_sb becomes Drink Hot Java! Cheer!

COMP201 Java Programming

COMP201 Topic 2 / Slide 2. Objective and Outline. ○ Objective. ▫ Show basic programming concepts. ○ Outline. ▫ What do java programs look like? ▫ Basic ingredients. – Java primitive types. – Variables and constants. – Operators and control flow. ▫ Simple commonly used built-ins. – Simple input/output. – Arrays and ...

475KB Sizes 2 Downloads 206 Views

Recommend Documents

Introduction to Java Programming
LiveLab is a programming course assessment and management system. Students can .... B MySQL Tutorial. C Oracle Tutorial. D Microsoft Access Tutorial. E Introduction to Database Systems. F Relational Database Concept. G Database Design ...... In 1954,

FRC Java Programming - GitHub
FRC Java Programming Last Updated: 1/11/2016 ..... NI Update Service .... network. When you have entered the team number and the roboRIO is connected, ...

Introduction to Java Programming
problem-driven complete revision new problems early console input hand trace box multidimensional arrays. Sudoku problem simplified basic GUI earlier .... T Networking Using Datagram Protocol. U Creating Internal ..... the outset, it is helpful to re

JXTA_ Java P2P Programming
After you have selected OK, configuration files and directories will be written to disk and the platform will boot. Before the platform fully boots, you will be presented with a security login dialog that requests the name and password you chose in t

Java Network Programming
class ClientTCP { public static void main(String args[]) throws UnknownHostException, IOException {. Socket s=new Socket("www.upv.es",80);. Scanner in=new Scanner(s.getInputStream());. PrintWriter out=new PrintWriter(s.getOutputStream(),true); out.pr

pdf-1879\programming-android-java-programming-for-the-new ...
Try one of the apps below to open or edit this item. pdf-1879\programming-android-java-programming-for-the-new-generation-of-mobile-devices.pdf.

pdf on java programming language
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. pdf on java ...

introduction-to-java-programming-comprehensive-9th-edition.pdf ...
introduction-to-java-programming-comprehensive-9th-edition.pdf. introduction-to-java-programming-comprehensive-9th-edition.pdf. Open. Extract. Open with.

Effective Java: Programming Language Guide
Jun 1, 2001 - the examples, you may have to add one or both of these import ..... A unifying theme underlies this Item and Item 21, which describes the ...

Introduction to Programming Using Java
languages such as Java, Pascal, or C++. A program written in a ...... If I say “the President went fishing,” I mean that George W. Bush went fishing. But if I say.

Advance Java Programming Techniques.pdf
products remains at the sole discretion of Oracle. Page 3 of 49. Advance Java Programming Techniques.pdf. Advance Java Programming Techniques.pdf. Open.