1.IF/FOR
if (condition) {
for (int i = 0; i < args.length; i++) {
xxx;
}
2.PRIMITIVE DATATYPES
int a = 1; 4
long b = 1L; 8
short c = 3; 2
byte d = 3; 1
char a = 'A'; 2
boolean j = true; 1
float a = 1.1f; 4
double a = 33.3; 8
3.BASIC BLOCK
switch (args) {
case value:
break;
...
default:
break;
}
do {
} while (condition);
one: while (condition) {
break one;
}
4.CLASS
1.declare:
class Hello{
//declare instance variables
type var1;
...
type method1(){
...
}
}
//declare an object that means an instance;
Hello demo = new Hello() ;
// equals :
// Hello demo ; reference of object
// demo = new Hello() ; allocate a Hello object ;
demo.var1 = xxx ;
2. method /void return
return-type methodName(parameter list ... ){
...
}
//void return -> return ;
3.user input
public class test {
public static void main(String[] args) throws java.io.IOException {
char ch;
ch = (char) System.in.read();
System.err.println(ch);
}
}
4. constructor
SayHello demo;
demo = new SayHello();
demo.person=" Alex Maodali";
demo.say();
demo.person = "Alex Maodali";
//this is not professional written pattern
//use constractor instead:
//a constractor is to initialize an object when it is created(or STACK BLOCK)
//it has the same name as the class and no extact/explicit return type;
class demo{
int a;
demo(){
a=2;
}
}
demo d=new demo();
print(demo.a)//result is 2
4.1 parameterized constructor
class Demo{
int a;
Demo(int i){
a=i;
}
Demo(int ... v){
a=v[3]
}
}
Demo s=new Demo(33);
demo.a//33
5.the New operator
class-var = new class-name(arg-list);//return an real object
6.the garbage collection
//the memory is not infinite ,so the garbage collection automatically execute when the program running
7.finalize method
finalize method execute just before the garbage collection
protected void finalize() throws Throwable {
// TODO Auto-generated method stub
super.finalize();
}
8.demostrate garbage collection
class Demo {
int x;
Demo(int i) {
x = i;
}
void generator(int i) {
Demo ob = new Demo(i);
}
protected void finalize() {
System.err.println("Finalizing..." + x);
}
}
class Finalize {
public static void main(String[] args) {
int count;
Demo ob = new Demo(0);
/*
* Now, generate a large number of objects. At
* some point, garbage collection will occur.
* Note: you might need to increase the number
* of objects generated in order to force
* garbage collection.
*/
for (count = 1; count < 100000; count++) {
ob.generator(count);
}
}
}
9.this keyword
return val;//this is the shorthanded written patton
return this.val;
void demo(String name){
this.name=name//this is used to hide the instance variables,the first name is refering to the instance not the paremeter;
}
5.ARRAY STRING BITWISE
1.Array:
1. one-dimensional array
int arr[]=new int[3];
int arr[]={1,34,4};
arr[]=new int[3];
int[] arr=new int[3];
for(int i=0;i<arr.length;i++;){
xxx;
}
int[][] arr=new int[3][4]
2. for-each loop
for (int i : arrlist ) sum+=i;//read only by i(FOR-EACH is READ-ONLY)
//i is arrlist[i]'s value
int[][] arr = new int[3][3]
for(int x[] : arr){
for (int i : x )
}
2.String
String str="xxx";
1.operate
boolean str1.equals(str2)
int length()
char charAt(index)
int compareTo(str)
int indexOf(str)
int lastIndexOf(str)
String substring(int stratindex,int endindex)//not include the end index
2.String on switch
String a="hello";
swich(a){
case "hello":
print(xx);
...
}
// In other words, don’t use strings in a
// switch unnecessarily.
3.String array
String[] a={"eee","de,p"}
6. PUBLIC/PRIVATE OVERLOAD
1.Public & Private
//public menber can be accessed in the inside of its defination class and the outside
//Private only be accessed in the defination class inside;
public class test {
public static void main(String[] args) {
hello demo=new hello();
System.err.println(demo.name);
System.err.println(demo.id); //wrong
}
}
class hello{
public String name;
private int id;
hello(){
name="default";
id=0;
}
}
2.overload method
public class test {
public static void main(String[] args) {
hello demo = new hello();
System.err.println(demo.db(3));
System.err.println(demo.db(33.3));
}
}
class hello {
int db(int a) {
return a * 2;
}
double db(double a) {
return a * 2;
}
long db(long a) {
return a * 2;
}
}
3.overload constractor
class demo{
int i;
demo(int i){
x=i;
}
demo(double i){
x=i;
}
}
4.passobject
public class test {
public static void main(String[] args) {
Demo demo=new Demo();
System.err.println(demo.passobject("hello"));
}
}
class Demo {
String passobject(String oj) {
return new String(oj);
}
}
5.recursion
void d(int n){
n=3;
return d(n-1);
}
6.Static
the variables can be changed or affected by any object s
static int a=2;
//the static create and can be accessed by any objects just like a global variables
public class test {
public static void main(String[] args) {
// Demo demo=new Demo();
//the static method is not nessary to new a object;
//and its not use like object.xxx;and like className.xxx;
System.err.println(Demo.passobject("hello"));
}
}
class Demo {
static String passobject(String oj) {
return new String(oj);
}
}
6.1 static block
main:
//the static block start run when the object is allocted and can use to init static value
System.err.println(Demo.name);// alex
class:
static String name;
static {
name = "alex";
}
7.nested / inner class
class Outer{
class Inner
}
8.varargs
varargs is like an array:v.length,v[i]
int demo(int var1,double var2,int ... v){}
int demo(int var1,double var2,int ... v,double ... c){}//error:there is only exist one varargs
- overloadign varargs method:
void demo(int ... v)
void demo(double ... v)
void demo(String ... v)
varargs and ambiguity
void demo(int ... v)
void demo(double ... v)
void demo(String ... v)
call:void demo()//which one is called? this is ambiguty
7.INHERITANCE
7.1 super
super(para-list)//call the fatherclass’s constractor
super.menber //call the fatherclass’s menber(method/variables)
childClass(int i,String name){
super(name);
super.a=i;
}
7.2
//all the constructor executed follow the derivation
class SuperClass{
private String name;
SuperClass(String name){
}
}
7.3 Method overide
when the subclass has the same return type and signature there is method overide
class A{
void show(){
//a=1;
print('d');
}
}
class B extends{
void show(){
print("in B");
}
}
main:
B v=new B();
v.show();//in B
7.4 Method overload
class A{
void show(){
//a=1;
print('d');
}
}
class B extends A{
void show(String a){
print("in B"+a);
}
}
main:
B v=new B("hello");//call B show:in Bhello;
v.show();//call A show : d;
7.5 dynamic method dispatch / method overide polymorhism
class A{
void ps(){
print("A");
}
}
class B extends A{
void ps(){
print("B");
}
}
class C extends A{
void ps(){
print("C");
}
}
main:
A a=new A();
B b=new B();
C c=new C();
A ref;
ref=a;
a.ps()//A
ref=b;
a.ps()//B
ref=c;
a.ps()//C
7.6 abstract
> abstract type name(para-list);
> abstract class className{...}
//The abstract modifier can be used only on instance
//methods. It cannot be applied to static methods or to constructors.
//the subclass must override the abstract method
abstract class sup{
void method1(){
xxx;
}
abstract void absMd(para-list);
}
class sub extends sup{
void absMd(String ...){
...
}
}
main:
sup s[]=new sup[2];
s[0]=new sub();
s[0].absMd();
7.7 Final keyword
//You can use final keyword to restrain the subclass or other object to change something;
1.final prevent override
class A{
final void a(){
...
}
}
class B extends A{
void a(){}//error
}
2.final prevent inheritance
final class A{}
class B extends A{}//error can't subclass A
3.final constant / final variables
public class test {
public static void main(String[] args) {
A day = new A();
day.whichDay(day.Monday);
}
}
class A {
final int Monday = 1;
final int Tuesday = 2;
final int Wednesday = 3;
String[] day = {
"Monday",
"Tuesday",
"Wednesday",
};
void whichDay(int theDay) {
System.err.println(day[theDay - 1]);
}
}
4.final static menber
public class test {
public static void main(String[] args) {
A day = new A();
day.whichDay(A.Monday);
}
}
class A {
final static int Monday = 1;
final int Tuesday = 2;
final int Wednesday = 3;
String[] day = {
"Monday",
"Tuesday",
"Wednesday",
};
void whichDay(int theDay) {
System.err.println(day[theDay - 1]);
}
}
7.8 Object
8.Package and Interfaces
1. Package
package pkg1.pkg2.pkg3;
pkg1/pkg2/pkg3
package SomeTestJavaCode.bookpack;
//
public class BookDemo {
public static void main(String[] args) {
System.err.println("helo");
}
}
2.access:
3.Import
import packageName.className/*;
4.Interface
//access is public or not used
//if not used interface is only used to the other menber in its pkg;
access interface name{
ret-type method1(p-list);
ret-type method2(p-list);
ret-type method3(p-list);
//the method must be public
//if not implement all method then use abstract class
...
type var1=value;
...
}
class A extends B implements interface{
class-body
}
example:
public interface Hello{
void printHello(String var);
void printHaHaHa(String var);
}
class demo implements Hello{
String var;
public void printHello(String var){}
public void printHaHaHa(String var){}
}
4.1 interface references
//if A,B all use interface
//then
... interface Hello{...}
A a=new A();
B b=new B();
Hello ref;
ref=a;
ref.getNext();
ref=b;
ref.getNest();
4.2 interface variables
// As mentioned, variables can be declared in an interface, but they are implicitly public, static, and final
public interface name{
String ERRORMSG="ERROR:401";
}
4.3 extends interface
public interface A{}
public interface B extends A{}
//when implement the interface B ,
// the method in interface A & B are all needed to be override
4.4 default method in interface
public interface A{
default int getSpecial(){return 1;}
int getNomal(String var){return var;}
}
class B implements A{
int getNomal()//this method is needed to override
//if u not override the default method ,the default method is automatically used
}
Main:
B b=new B();
b.getNomal();//call this in B method
b.getSpecial();//which is the default in A interface
NOTE:
First, in all cases a class implementation takes priority over an interface default
implementation. Thus, if MyClass provides an override of the reset( ) default method,
MyClass’s version is used. This is the case even if MyClass implements both Alpha and Beta.
In this case, both defaults are overridden by MyClass’s implementation.
Second, in cases in which a class inherits two interfaces that both have the same default
method, if the class does not override that method, then an error will result. Continuing with
the example, if MyClass inherits both Alpha and Beta, but does not override reset( ), then an
error will occur.
> if beta wants to use alpha's implemention and beta extends alpha:
> alpha.super.methodNameInAlpha();
4.5 static method in interface
public interface interfaceName{
void methodName1(){}
default void methodName2(){}
static int methodName3(){}
}
use:
> int staticMethod=interfaceName.methodName3();
9.Exception Handle
9.1 Throwable
Throwable = Error + Exception
//Error means ERROR in JVM
//Exception means ERROR in u program
keyword
try / catch / throw / throws /finally
package SomeTestJavaCode.bookpack;
/**
* BookDemo
*/
public class BookDemo {
public static void main(String[] args) {
int[] a=new int[3];
try {
// a[3]=3;
throw new ArrayIndexOutOfBoundsException();
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {//muti-catch
// TODO: handle exception
System.err.println();
System.err.println("Stander errormsg is: ");
System.err.println(e);
System.err.println();
System.err.println("Stack trace is: ");
e.printStackTrace();
System.err.println();
throw e;
}finally{
System.err.println("finally");
}
}
}
9.2 thorws
ret-type methodName(parameter-list) throws except-list{
//body
}
9.3 subclass of exception
class THISISMYERROR extends Exception{
int i;
THISISMYERROR(int i){
this.i=i;
}
public String toString(){
if (i>0) print("something error");
}
}
try{
}catch(){
...
throw new THISISMYERROR(2);
}
10.I/O Stream
10 byte-streamed i/o
10.1 console input
int read(byte data[]) throws IOException
package SomeTestJavaCode.bookpack;
import java.io.IOException;
/**
* BookDemo
*/
public class BookDemo {
public static void main(String[] args)
throws IOException {
byte data[] = new byte[10];
System.err.println("Please Enter:");
System.in.read(data);
System.err.print("You Entered: ");
for (int i = 0; i < data.length; i++) {
System.err.print((char) data[i]);
}
}
}
10.2 console write
package SomeTestJavaCode.bookpack;
/**
* BookDemo
*/
public class BookDemo {
public static void main(String[] args) {
System.err.println("hello");
System.err.print("hello");
}
}
10.3 File Operation
To create a byte stream linked to a file, use FileInputStream or FileOutputStream.
10.3.1 input file
FileInputStream(String fileName) throws FileNotFoundException
int read( ) throws IOException
void close( ) throws IOException
10.4 charactered-based streams
10.4.1 console input
constractor:
InputStreamReader(InputStream inputStream)
BufferedReader(Reader inputReader)
Putting it all together, the following line of code creates a BufferedReader that is connected to
the keyboard.
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
//
Here are three versions of read( )
supported by BufferedReader.
int read( ) throws IOException
int read(char data[ ]) throws IOException
int read(char data[ ], int start, int max) throws IOException
//
//read a string
//String readLine( ) throws IOException
package SomeTestJavaCode.bookpack;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class BookDemo {
public static void main(String[] args)
throws java.io.IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String var;
System.err.println("Enter lines of text");
System.err.println("Use stop to quit");
do {
var = br.readLine();
System.err.println(var);
} while (!var.equals("stop"));
}
}
10.4.2 console output
// Demonstrate PrintWriter.
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
int i = 10;
double d = 123.65;
pw.println("Using a PrintWriter.");
pw.println(i);
pw.println(d);
pw.println(i + " + " + d + " is " + (i+d));
}
}
10.5 file writer
package SomeTestJavaCode.bookpack;
import java.io.*;
public class BookDemo {
public static void main(String[] args)
throws IOException {
String str;
InputStreamReader ips = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ips);
System.err.println("'stop' to quit");
try (FileWriter filewriter = new FileWriter(
"E:\\WorkingHere\\NOTES\\FullStack\\SomeTestJavaCode\\bookpack\\test.txt");) {
do {
System.err.print(">>>");
str = br.readLine();
if (str.compareTo("stop") == 0) {
break;
}
str = str + "\r\n";
filewriter.write(str);
} while (str.compareTo("stop") != 0);
} catch (IOException exc) {
System.err.println("I/O ERROR: " + exc);
}
}
}
//fileName is the full path name of a file.
//If append is true, then output is appended to
// the end of the file. Otherwise, the file is overwritten
10.6 file reader
package SomeTestJavaCode.bookpack;
import java.io.*;
public class BookDemo {
public static void main(String[] args) {
String str;
// create a file reader
try (BufferedReader br = new BufferedReader(
new FileReader("E:\\WorkingHere\\NOTES\\FullStack\\SomeTestJavaCode\\bookpack\\test.txt"))) {
while ((str = br.readLine()) != null) {
System.err.println(str);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
10.8 the NIO
10.9 wrapped type
int n;n = Integer.parseInt(str);
11. MutiTread Programing in Java
To create
a new thread, your program will either extend Thread or implement the Runnable interface.