Senior Pimiento

Основы Java

Hello World

public class HelloWorld {
  public static void main(String args[]) {
    System.out.println("Hello World!");
  }
}
Hello World!

jar

Create archive

jar cfe name.jar EntryPointClass A.class B.class C.class

List jar content

jar tf hw.jar
META-INF/
META-INF/MANIFEST.MF
HelloWorld.class

Exctract jar archive

jar xf name.jar

Run jar archive with entry point

java -jar hw.jar
Hello World!

Run jar archive without entry point

java -cp hw.jar HelloWorld
Hello World!

Primitive Types

Type Definition
boolean true or false
char 16-bit, Unicode character
byte 8-bit, signed, two\u2019s complement integer
short 16-bit, signed, two\u2019s complement integer
int 32-bit, signed, two\u2019s complement integer
long 64-bit, signed, two\u2019s complement integer
float 32-bit, IEEE 754, floating-point value
double 64-bit, IEEE 754

floating-points precision

If you want to ensure that your application produces exactly the same results on
different platforms, you can use the special keyword strictfp as a class modifier
on the class containing the floating-point manipulation.

default initialization

numeric types default to the appropriate flavor of zero,
characters are set to the null character (\0),
and Boolean variables have the value false.
Local variables, which are declared inside a method and live only for the duration of a method call,
on the other hand, must be explicitly initialized before they can be used.

Switch

takes an integer (or a numeric argument that can be automatically "promoted" to an integer type), a String type argument, or an "enum" type and selects among a number of alternative, constant case branches.

break & contiune labels

The break and continue statements look like those in the C language, but Java's forms have the additional ability to a label as an argument and jump out multiple levels to the scope of the labeled point in the code.

/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = {
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

null

The expression null can be assigned to any reference type. It means "no reference". A null reference can't be used to reference anything and attempting to do so generates a NullPointerException at runtime.

catch

In Java 7, there is an alternative to using multiple catch clauses, and that is to handle multiple discrete exception types in a single catch clause using the &vert; or syntax:

try {
    // read from network…

    // write to file…

} catch (ZipException | SSLException e) {
    logException( e );
}

Using this &vert; or syntax, we receive both types of exception in the same catch clause. So, what is the actual type of the e variable that we are passing to our log method? (What can we do with it?) In this case, it will be neither ZipException nor SSLException but IOException, which is the two exceptions' nearest common ancestor (the closest parent class type to which they are both assignable). In many cases, the nearest common type among the two or more argument exception types may simply be Exception, the parent of all exception types.

printStackTrace

try {
    // complex, deeply nested stack

} catch (Exception e) {
    // dump information about exactly where the exception occured

    e.printStackTrace(System.err);
}

own exceptions

class ParseException extends Exception {
    ParseException() {
        super();
    }
    ParseException( String desc ) {
        super( desc );
    }
}

exceptions chaining

try {
} catch ( IOException cause ) {
    Exception e = new IOException("What we have here is a failure to communicate…");
    e.initCause( cause );
    throw e;
}

Assertions

The optional expression may evaluate to either a primitive or object type. Either way, its sole purpose is to be turned into a string and shown to the user if the assertion fails; most often you'll use a string message explicitly.

assert false;
assert (array.length > min);
assert a > 0 : a                   // shows value of a to the user

assert foo != null : "foo is null" // shows message "foo is null" to user
  • To enable assertions, use flag -ea or -enableassertions
java -ea MyApplication
  • To turn on assertions for a particular class, append the class name
java -ea:examples.MyClass MyApplication
  • To turn on assertions just for particular packages, append the package name with trailing ellipses (…)
java -ea:examples...MyApplication
  • To disable assertions in general, for a particular class or for a particular package, use flag -da or -disableassertions. You can combine all this to achieve arbitrary groupings
java -ea:examples... -da:examples.text -ea:examples.text.MonkeyTypewriters MyApplication

Arrays

Java supports the C-style curly braces construct for creating an array and initialize its elements

int [] primes = {2, 3, 5, 7, 7+4};

We can use curly braces syntax also to create anonymous arrays.

Good OOP design practices

  1. Hide as much of your implementation as possible. Define accessor methods to set and return values.
  2. Use composition instead of inheritance. Do you really need to inherit the whole public interface of an object (to be a "kind" of that object) or whether you can just delegate certain jobs to the object and use it by composition.
  3. Minimize relationships between objects and try to organize related objects in packages. The more loosely coupled your objects are, the easier it will be to reuse them later.

varargs

void printObjects (Object ... list) {
    for (Object o : list)
        System.out.println( o );
}

Inside the printObjects method, the variable list is actually an Object [] type.

public class VarargsTest {
  static int zeroArray (int[] numbers) {
    return numbers[0];
  }

  static int zeroVarargs(int ... numbers) {
    return numbers[0];
  }

  public static void main(String args[]) {
    System.out.println(zeroArray(new int[]{1, 2, 3, 4}));
    System.out.println(zeroVarargs(1, 2, 3, 4));
  }
}
1
1

constructor and this method

You can invoke a second constructor (delegate to it) only as the first statement of your constructor. For example, the following code is illegal and causes a compile-time error:

class Car {
    Car(String m) {
        int doors = someMethod();
        this(m, doors);         // Error: constructor call must be first statement

    }
}

The simple model name constructor can't do any additional setup before calling the more explicit constructor. It can't even refer to an instance member for a constant value:

class Car {
    ...
    final int default_doors = 4;
    ...
    Car(String m) {
        this(m, default_doors); // Error: referencing uninitialized variable

    }
    ...
}

The instance variable defaultDoors is not initialized until a later point in the chain of constructor calls setting up the object, so the compiler doesn't let us access it yet. Fortunately, we can solve this particular problem by using a static variable instead of an instance variable:

class Car {
    ...
    static final int DEFAULT_DOORS = 4;
    ...
    Car(String m) {
        this(m, DEFAULT_DOORS); // OKAY

    }
}

The static members of a class are initialized when the class is first loaded into the virtual machine, so it's safe to access them in a constructor.

Initializer blocks

It's executed once, at the time the object is constructed, or, in the case of a code block marked static, at the time the class is loaded

class MyClass {
    Properties myProps = new Properties();
    // set up myProps

        {
            myProps.put("foo", "bar");
            myProps.put("boo", "gee");
        }
    int a = 5;
    ...
}

It allows the static members of a class to have complex initialization just like objects do with constructors:

class ColorWheel {
    static Hashtable colors = new Hashtable();

    // set up colors

    static {
        colors.put("Red", Color.red );
        colors.put("Green", Color.green );
        colors.put("Blue", Color.blue );
        ...
            }
    ...
}

The first time the class ColorWheel is referenced and loaded, the static components of ColorWheel are evaluated in the order they appear in the source.

String examples

public class StringConcat {
  public static void main(String args[]) {
    System.out.println("A" + 12);
    System.out.println('A' + "12");
    System.out.println('A' + '1' + "2");
    System.out.println("A" + ('\t' + '\u0003'));
  }
}
A12
A12
1142
A12
public class StringReverse {
  public static boolean isPalindrome(String text) {
    String s = new String(text.toLowerCase().replaceAll("[^a-zа-я0-9]", ""));
    return (new StringBuilder(s).reverse().toString()).equals(s);
  }

  public static void main(String args[]) {
    System.out.println(isPalindrome("рсфср"));
    System.out.println(isPalindrome("ссср"));
    System.out.println(isPalindrome("Madam I'm Adam"));
    System.out.println(isPalindrome("А роза упала на лапу Азора"));
  }
}
true
false
true
true