learningbydeveloping.com

 

Learning by developing

...because practice teaches you

PDF version:scjp T-6

String class:

String s1= “”+7+3; //Contains “7 3″

String s2 = 7+3 + “”+ 9+5; //Contains “10 9 5″

Note: Strings are static and changing the string means creating new reference. StringBuffers/readers can change their state, are not synchronyzed and thread safe. Equals() used between StringBuffers will return false if the objects are different, even if they contain the same String

Some of the most important methods of the String class are:

charAt

concat

equals

equalsIgnoreCase

length

replaceChar

substring

toLowerCase

toString

toUpperCase

trim

append

delete

insert

reverse

StringBuffers/builders: compare references(they are objects) not values. Additionally, readers have NO flush().

String Buffer/Builder:

StringBuffer contains the same API as the StringBuilder but it is thread safe(StringBuilder is NOT thread safe),but it is slower.

File: represents the pathname of the file/directory. Create/search/delete file/directory(not write). Note:File DOES NOT support changing the directory

import java.io.File;

//Declares the file class using the import

File file = new File(“file.txt”);

//We can also use it without using import

java.io.File file = new java.io.File(“file.txt”);

File methods and attributes:

Exits() method: checks if the file/directory exists.

File.separator: The system-dependent default name-separator character, represented as a string for convenience. Note: Unix the separator is /. So if you wanted to build the unix path /var/temp you would do it like this:

String path = File.separator + “var”+ File.separator + “temp”

File.pathseparator: The system-dependent path-separator character, represented as a string for convenience

/jar1.jar:/path/to/jar2.jar:/path/to/jar3.jar

FileReader/FileWriter: Read char-based files.

BufferedReader/BufferedWriter: wrapper of FileReader/FileWriter which uses buffers to increase the efficiency. Provides of read/write lines.

PrintWriter: writer with more methods(format(), printf(), append()).

Important: flush() are only called in bufferedWriters. Readers have no flush() methods.

File API:

Class

Extends from

Key methods

File

Object

createNewFile, delete, exists, isDirectory, isFile, list, mkdir, renameTo

FileWriter

Writer

close,flush,write

BufferedWriter

Writer

close,flush, newLine, write

PrintWriter

Writer

close,flush,write, format, printf, printb, println

FileReader

Reader

read

BufferedReader

Reader

read, readLine

File:

  • createNewFile();<– until this method is called, the file does not exist.

  • mkDir(filesystem);

Example: creation of a file.

 

Using FilerReader and fileWriter:

 

Working with directories:

Console: It is used to obtain an instance of the console which is used(if it is a console application(no UI), else it would return null). Created through “java.io.Console” and “System.console()” E.g.:

 

System.Console c = new System.console();

string s1 = c.readPassword(“[%s]”, “Password:”); //IMPORTANT: readPassword returns char[], not string

string s2 = c.readline(“%s”, “username:”);

Note: check that “%s” = string and “[%s]” is a char array so that, in password “%s” would give an error.

//IMPORTANT: The console CANNOT be configured to avoid echoing user password unless you override the readPassword() to do something like:

public char[] readPassword() {

return readPassword(“”);

}

Object serializing: All attributes of an object will be serialized except the ones tagged as “transient“(which will have their primitive default value,so for an int it would be 0(even if the object has transient int x =8;) or “static”(which is not an object’s attribute but a class one,so it would have the same values for all the objects of that class).

IMPORTANT: If the object does not have attributes, we don’t need to have any method to serialize even if the class “implements Serializable”. The Serializable interface does not have any methods or fields, serves only to idenfity the semantics of being serializable.

IMPORTANT 2:

  • Serialization(writing/reading file): B extends A. B serializable, constructor is NOT called when reading from file, A is NOT serializable , then A() is called. So only the constructor of the NON-serializable classes is called.

  • On the other hand if ‘B’ HAS-A ‘A'(attribute) then A should implement serializable or it will throw an exception(because it tries to serialize all the attributes and ‘A’ is not serializable.

We can serialize objects with the classes(Note this could be done in a static-main method). :

ObjectOutputStream.writeObject();

ObjectInputStream.readObject();

//Serialize Object: The serialized objectMUST implement serializable(though it can extend a non-serializable class, which constructor would be called).All its attributesmust be either static/volatile(which are not serialized) or must be serializable, else it will throw a NotSerializableException.

//Deserialize the object:Only constructors of NON-SERIALIZABLE objects are called

Note: FileInputStream will throw during its creation “FileNotFoundException” if the file does not exist.

If we have an object which we want to serialize/deserialize, we should implement some “serializable” interface’s methods:

private void writeObject(ObjectOutputStream os)

private void readObject(ObjectInputStream is)

Note: readObject should call to “is.defaultReaderObject()” which indicates the class to serialize normally and read writeObject should call “os.defaultWriterObject()” which indicates the class to deserialize normally.

E.g.: We create an object by reading the attributes and creating the object and the same to write(same order!).

ReadObject/WriteObject:

 

Summary of Locales, Dates and Calendar: It is important to know their constructors:

 

Note: Date does not have format() method, to format a Date we need a DateFormat

E.g.: Prints a date(given the milliseconds from Jan 1,1970 in LONG format(DateFormat.LONG) with Locale of Germany(Locale.GERMANY).

Import java.util.*; //import LOCALES

import java.text.*; //import Dateformat

Class DateTwo{

public static void main(String[] args){

     Date d = dew Date (11111110000L);

     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG,Locale.GERMANY);

     System.out.println(“df.format:”+df.format(d));

 }

}

RegEx: language inside java/others or regular expressions. Note: $java regex2 “d*” ab34ef. In this example ‘d’ defines digit. * os 0 or many. So it finds 34 in position 2.

x?x : [0 or 1]

x*x : [0 or N]

x+x: [1 or N]

We will not enter into details, since regex is quite wide. I recommend to check courses about it if you are interested. I leave one example about how it works:

Example - Regex:

Text: “1012 0208 430″

Regular expression:

a) “0([0-7])?”It means one 0 and 0-1 character(from 0 to 7) “?”finds only 1 character after 0.

Text:”1012 0208 430″

“1012 02 08 430

so

match.start()

match.end()

match.group()

1

2

01

4

5

02

6

6

0

10

10

0

It does not take 08 because 8 is not between 0 and 7

Regular expression:

a) “0([0-7])*”It means one 0 and 0-N characters(from 0 to 7).

Text:”1012 0208 430″

“10120208 430

so

match.start()

match.end()

match.group()

1

2

012

4

6

020

10

10

0

It does not take 0208 because 8 is not between 0 and 7

Regular expression:

a) “0([0-7])+”It means one 0 and 1-N characters(from 0 to 7).

Text:”10120208 430″

“10120208 430

so

match.start()

match.end()

match.group()

1

2

012

4

6

020

It does not take 0208 because 8 is not between 0 and 7

It does not take the last 0, because it does not have any [0-7](1 or more for ‘+’) following it.

 

 

**********************************************

The books I have used are these ones, which I strongly recommend. You can support this blog buying them through this links:

 

and

 

For OCJP version 7, I would recommend:

 

 

Categories: Java

Leave a Reply