You are on page 1of 34

Java I

Indian Statistical Institute

(ISI) Java I 1 / 33
Outline

1 Program structure

2 Object oriented programming (constructors, inheritance, public, private, etc.)

3 Language basics

4 Useful classes

5 Exceptions

6 Odds and ends

(ISI) Java I 2 / 33
Program structure

import java.io.* ; Similar to #include


class Hello { File name must match class name.
private int x, y;

public char c, d;
}Variables
public Hello(char c, char d) { Constructor
this.c = c; Order
this.d = d; does
}
not
public void someFunction() { Methods matter.
/* some code here */ (functions)
return;
}

private void privateMethod() {


/* some code here */ Rest of the
return;
program must be
}
inside a class.
(ISI) Java I 3 / 33
Program structure

/* Need main() if this is to be run as a standalone program (as


* opposed to a class that will be used by other programs).
*/
public static void main(String[] args) {
Hello h; h is a reference,
initially null.
h = new Hello('a', 'b'); h points to object / instance of class Hello.
System.out.println("" + h.c + h.d);
}
} // End of class Hello

(ISI) Java I 4 / 33
Outline

1 Program structure

2 Object oriented programming (constructors, inheritance, public, private, etc.)

3 Language basics

4 Useful classes

5 Exceptions

6 Odds and ends

(ISI) Java I 5 / 33
Constructors

public Hello(char c, char d) {


this.c = c;
this.d = d;
}

Used to create a new object (cf. malloc())


Has same name as class, no return type
Possible to define multiple constructors for a class, with different
calling conventions
Garbage collection → automatic (no equivalent of free())

(ISI) Java I 6 / 33
Inheritance

Subclass Superclass
import java.io.* ;

class SpecialHello extends Hello {


// Variables and methods of Hello inherited by default
// New variables / methods for this subclass
public String msg;

public SpecialHello(char x, char y, String s) {


super(x, y);
this.msg = s;
}

public static void main(String[] args) {


SpecialHello sph;
sph = new SpecialHello('a', 'b', "Message in the subclass");
System.out.println("" + sph.c + sph.d + sph.msg);
}
} // End of class SpecialHello

Method in subclass automatically overrides method with same


name and parameters in any superclass.
(ISI) Java I 7 / 33
Access modifiers I

public: visible outside the class (constructors must be public)


private: internal, only visible inside the class
protected: only visible within class and in subclasses
final: constants (cannot be changed once set)

Default visibility ≈ public

(ISI) Java I 8 / 33
Access modifiers II

static
associated with class, not with any specific instance / object
only one instance of the variable / function across all instances of the
class (≈ “global”)
exists even if class is never instantiated
static methods cannot access any variables

example uses:

int i = 20, j = 200;


Integer I = 1;
i = Integer.parseInt("10");
j = I.parseInt("100");
System.out.println(Math.tan(j) + " " + Math.PI);

(ISI) Java I 9 / 33
Access modifiers III

abstract:
declarations without any associated implementation
method must be implemented in subclasses
class with abstract method(s) → abstract class
abstract class cannot be instantiated with new

(ISI) Java I 10 / 33
Outline

1 Program structure

2 Object oriented programming (constructors, inheritance, public, private, etc.)

3 Language basics

4 Useful classes

5 Exceptions

6 Odds and ends

(ISI) Java I 11 / 33
Primitive / basic data types

Type name Size / range of values


boolean true, false
byte 8 bit signed
char 16 bit unsigned (Unicode character)
short 16 bit signed
int 32 bit signed
long 64 bit signed
float 32 bit
double 64 bit

Casting
Syntax as for C, except underscores permitted and ignored
Automatic casting only when conversion is guaranteed to be lossless
(ISI) Java I 12 / 33
Conventions for variable, function, class names

Classes: MixedCase, starting with uppercase letter


e.g., StringBuffer
Constants (final): ALL_UPPER_CASE, with words separated by
underscores
e.g., final float INTEREST_RATE = 0.04;
Other names (functions, variables): mixedCase, starting with
lowercase letter
e.g., int maxValue;

A note about variables


Store primitive values (see above), or references (pointers) to objects
Cannot store objects
Not possible to create pointer to primitive value

(ISI) Java I 13 / 33
Wrapper classes for primitive types

Boolean, Byte, Character, Short, Integer, Long, Float, Double

Examples
Character.isDigit(’3’); // true
Character.isUpperCase(’a’) // false
Character.toUpperCase(’a’) // ’A’

Integer i = 3;
i = new Integer(3);

int j = i.intValue();
j = Integer.MAX_VALUE;
j = Integer.parseInt("123"); // like atoi()

String s = Integer.toHexString(123); // "7b" (123 in hex)

double x = Double.parseDouble("123e-2"); // like atod()

(ISI) Java I 14 / 33
Expressions, statements, method calls

Arithmetic, logical, comparison, ternary operators: as in C


if, switch, for, while, do-while: as in C
For-each loops: useful for iterating over arrays / collections
int[] numbers = {1, 2, 3, 4};
for (int number : numbers) { /* do something */ }

Methods use call by value


changes in called function to a primitive type parameter do not affect
value in calling function
changes in called function to object do affect object in calling function

(ISI) Java I 15 / 33
Input/output

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));
// OR
BufferedReader in = new BufferedReader(new FileReader("somefile"));

System.out.print(); System.out.println();

Scanner scanner = new Scanner(System.in);


double number = scanner.nextDouble();
byte number = scanner.nextByte();
String name = scanner.next();
String line = scanner.nextLine();

(ISI) Java I 16 / 33
Outline

1 Program structure

2 Object oriented programming (constructors, inheritance, public, private, etc.)

3 Language basics

4 Useful classes

5 Exceptions

6 Odds and ends

(ISI) Java I 17 / 33
Strings I

Holds (Unicode) chars, NOT bytes


No ’\0’ at end
Immutable (cf. StringBuffer)

String concatenation
Concatenation operator: +
Possible to concatenate anything with a string
Objects should provide toString() method(s)
(library classes all have reasonable toString() methods)

(ISI) Java I 18 / 33
Strings II

String str = "This is a string." ;

System.out.println(str.length() + " " + str.charAt(0) + " " +


str.charAt(str.length() - 1));

// substring(startIndex, endIndex+1)
int i;
for (i = 0; i < str.length(); i++)
if (str.charAt(i) == str.substring(i, i+1).charAt(0))
System.out.print(".");
System.out.println(" sanity check.");

// split(regularExpression)
String[] words = str.split("\\s+");

// Tokenisation
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()) {
String s = tok.nextToken();
System.out.println(s);
}

(ISI) Java I 19 / 33
Strings II

String str = "This is a string." ;

System.out.println(str.length() + " " + str.charAt(0) + " " +


str.charAt(str.length() - 1));

// substring(startIndex, endIndex+1)
int i;
for (i = 0; i < str.length(); i++)
if (str.charAt(i) == str.substring(i, i+1).charAt(0))
System.out.print(".");
System.out.println(" sanity check.");

// split(regularExpression)
String[] words = str.split("\\s+");

// Tokenisation
StringTokenizer tok = new StringTokenizer(str);
while (tok.hasMoreTokens()) { StringTokenizer() takes as
String s = tok.nextToken();
System.out.println(s); optional second argument a string
} containing separator characters
(defaults to whitespace).
(ISI) Java I 20 / 33
Strings III

Other useful functions


String s = "abcdef", t = "defxyz", u, v;

s.startsWith("a"); // true
t.endsWith("f"); // false

s.indexOf(’d’); // 3
s.indexOf("def"); // 3
t.lastIndexOf(’x’); // 3

t.toUpperCase(); // "DEFXYZ"
u = t.replace("xyz", "def"); // "defdef"
v = "ABCDEF".toLowerCase(); // "abcdef"

s == v; // false
s.compareTo("abc"); // > 0 (like strcmp())
s.compareTo(v); // == 0 (like strcmp())
s.equals(v); // true

(ISI) Java I 21 / 33
Arrays

int[] a = { 2, 1, 3 }; // reference to an array

{
Arrays.sort(a); a.toString(a) does not work
System.out.println(Arrays.toString(a)); a.toString() does not work as
expected

a = new int[100]; // array of ints initialised to 0


Arrays.fill(a, -1); // now filled with -1 Initialisation
/* a.length == 100 */

Hello[] h = new Hello[10]; // array of (references to) Hello objects


/* h.length == 10 */

int[][] matrix = new int[10][20];

Arrays initialised with false / 0 / 0.0 / null by default


length field is final (i.e., cannot change array length)

(ISI) Java I 22 / 33
Vectors

import java.util.Vector;

Vector v = new Vector(); // empty


Similar to arrays, but can grow / shrink
for (int i=0; i<100; i++)
v.add(new Integer(i)); // v.add(i) works with warning
Array notation
v.set(5, 10); // like v[5] = 10
Object o = v.get(3); // like o = v[3]; not allowed

v.add(6, "world"); // elements v[7], v[8], ... shifted right


v.remove(3); // elements v[4], ... shifted left

for (int i=0; i<100; i++) {


Integer member = (Integer)(v.get(i));
int n = member.intValue();
System.out.println(n*n); Elements are of class Object (root class) ⇒
} • can insert objects of any type into Vector
• accessed element (type Object) has to be
before use

(ISI) Java I 23 / 33
Iterators

for (Iterator i = v.iterator(); i.hasNext(); ) {


int n = ((Integer)(i.next())).intValue();
System.out.println(n*n);
}

(ISI) Java I 24 / 33
HashMaps

HashMap table = new HashMap(); // empty table of key-value pairs

table.put("seven", new Integer(7)); // key = String "seven", value = 7


table.put("seven", 7); // produces warning as for Vector
Object o = table.put("seven", new Byte(1)); // returns previous value
int n = ((Integer) o).intValue(); // n = 7
o = table.get("seven"); // get current binding (Byte)
o = table.remove("seven"); // get current binding + remove it

table.containsKey("seven"); // true
table.containsKey("twelve"); // false

// Iterating over the keys


for (Iterator i = table.keySet().iterator(); i.hasNext(); ) {
Object key = i.next();
System.out.println(key + " -> " + table.get(key));
}

table.clear(); // remove all bindings

(ISI) Java I 25 / 33
Sets

HashSet s = new HashSet();

s.add("Black"); // true (but with warning)


s.add("White"); // true (but with warning)
s.add("White"); // false!
s.size(); // 2

for (Iterator i = s.iterator(); i.hasNext(); ) {


System.out.println(i.next());
}

(ISI) Java I 26 / 33
Outline

1 Program structure

2 Object oriented programming (constructors, inheritance, public, private, etc.)

3 Language basics

4 Useful classes

5 Exceptions

6 Odds and ends

(ISI) Java I 27 / 33
Exceptions

public int getInput() throws IOException {


... Any object (?)
if (...) {
throw new IOException("some error message");
}
}
public void someFunction() { Either handle exception(s)
... via try - catch
try {
getInput();
processInput(); // not executed if getInput() throws exception
}
catch (IOException e) { /* Take corrective action */ }
catch (SomeOtherException f) { /* Take corrective action */ }
finally { or declareexecution
Always executed (whether they won’t be
... handled
leaves try normally / via via throws/
exception
}
} return / break / continue).

(ISI) Java I 28 / 33
Outline

1 Program structure

2 Object oriented programming (constructors, inheritance, public, private, etc.)

3 Language basics

4 Useful classes

5 Exceptions

6 Odds and ends

(ISI) Java I 29 / 33
Misc. issues

Sizes of types, order of evaluation are specified.


User-defined operator overloading is not allowed.
== corresponds to object identity, not content identity.
args[0] (argument to main()) is first command-line argument, not
command name.
Use jshell ($JAVA_HOME/bin/jshell in modern versions) to
quickly test small code snippets

(ISI) Java I 30 / 33
Cloning

Coming soon

(ISI) Java I 31 / 33
Sources / references I

Tutorials / crash courses / quick overviews


http://orion.towson.edu/~mzimand/adatastruct/
Lect2-java-tutorial.html ∗ ∗ ∗
Java Cheat Sheet, Mosh Hamedani.
https://programmingwithmosh.com/wp-content/uploads/
2019/07/Java-Cheat-Sheet.pdf
Teach Yourself Java in 21 Minutes, Patrik Persson.
https://fileadmin.cs.lth.se/cs/Education/EDA040/common/
java21.pdf
Computer Science 333: Advanced Programming Techniques (Spring
2009), Brian Kernighan.
https://www.cs.princeton.edu/courses/archive/spring09/
cos333/javacrash.pdf

(ISI) Java I 32 / 33
Sources / references II

Cheatsheets
http://introcs.cs.princeton.edu/java/11cheatsheet/ ∗ ∗ ∗
http://github.com/amitguptagwl/Java-Rule-Book
http://github.com/cirosantilli/java-cheat
http://github.com/in28minutes/java-cheat-sheet
http://hackr.io/blog/java-cheat-sheet
http:
//www.edureka.co/blog/cheatsheets/java-cheat-sheet/
http://www.mindprod.com/jgloss/jcheat.html
http://www.paradise.caltech.edu/cook/Workshop/Java/
Overview.html
http://www.rankred.com/java-cheat-sheets/

(ISI) Java I 33 / 33
Sources / references III

Books
1. Core Java for the Impatient, Cay S. Horstmann.
Addison-Wesley / Pearson Education Inc.
2. Effective Java (3rd ed.), Joshua Bloch. ∗ ∗ ∗
Addison-Wesley / Pearson Education Inc.

Misc. resources
https://www.mindprod.com/jgloss/pointer.html
https://www.mindprod.com/jgloss/gotchas.html

∗ ∗ ∗ – recommended

(ISI) Java I 34 / 33

You might also like