Object & Methods
String s1; //Step 1: declare a String variable.
s1 = new String(); //Step 2: assign it a value: a new empty string.
first line create a box, store references in strings.
second line construct a brand new string object.
= create a reference
A syntax sugar in Java:
String s2 = new String();
s1 = "Yow!"; also creates a constructor with Yow in the box.
now s1 forget the last one and remembers yow instead of the empty one.
s2 = s1; // reference to the same object;
s2 = new String (s1); //now 2 different, identical objects.
3 String constructors:
- new String() constructs empty string - contains no character.
- "whatever"
- new String(s1) takes a parameter s1. Makes copy of object that s1 references.
Constructors always have the same name as their class, except "stuff in quotes".
s2 = s1.toUppercase();
String s3= s2.concat("!!"); // or just s2+"!!";
String s4 = "*".concat(s2).concat("*");//"*".concat(s2) compute first
In Java, String object are immutable unlike in C: their contents never change.
Java I/O Classes
Objects in System class for interacting with a user:
System.out is a PrintStream object that outputs to the screen.
System.in is an InputStream " " reads from the keyboard.
Actually, the two mentioned above should be variables that references to the object.
readLine method is defined on BufferedReader objects.
How do we construct a BufferedReader(compose into entire lines of text)? With an InputStream.Reader.
How .. an InputStreamReader(compose into characters typically 2 bytes)? We need an InputStream
How .. an InputStream(read raw data)? System.in is one.
Figure this out from online Java libraries API. Specifically, java.io library here.
import java.io.*;//to use the java library, other than java.lang
class SimpleIO{
public static void main(String[] arg) throws Exception{
BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in));
System.out.println(keybd.readLine());
}
-------------------------------------------------------------------------------------------------------
import java.net.*;
import java.io.*;
public class readURL {
public static void main(String[] arg) throws Exception{
URL u = new URL("http://www.bbc.co.uk");
InputStream s = u.openStream();
InputStreamReader inputrd = new InputStreamReader(s);
BufferedReader bbc = new BufferedReader(inputrd);
System.out.println(bbc.readLine());
}
}