Thinking in Java notes (1) 1 ~ 10

Source: Internet
Author: User

 

Thinking in Java notes (1 ~ 10)

 

1. Data Type testing

 

Class A {public int I; Public double D; public float F; public long l; Public Boolean B; Public char C; Public short S; Public byte ;} public class classtest {public static void main (string ARGs []) {A = new A (); system. out. println (". I = "+. i); system. out. println (". D = "+. d); system. out. println (". B = "+. b); system. out. println (". by = "+. by); system. out. println (". C = "+. c); system. out. println (". S = "+. s); system. out. println (". F = "+. f) ;}} the output result is:. I = 0. D = 0.0. C =. S = 0. F = 0.0. B = False. by = 0;

Explanation:

Because the local member variables are initialized by default, the default initialization of a character is a character with an ASCII value of 000.

The characters with an ASCII value of 000 are displayed as a (JDK 1.6.0.8) in DOS)

 

If int m is added to the classtest class, Initialization is required. Otherwise, an error is returned.

 

 

2. A class can be modified by public, static, and friendly.

 

 

Iii. static testing

 class A{                   public A(){              System.out.println("hello I am A ");             }                        static{                           System.out.println("hello I am A static");           }                                                               }          class  ClassTest{               static{                           System.out.println("hello I am ClassTest ");           }           public  static void  main(String args[]){                     A  a  =  new A();                                                                                                                      }         }   

Output result:

Hello I am classtest

Hello I am a static

Hello I am

Explanation: The static block is a static binding prior to the constructor. The generation of class objects is dynamic binding.

 

4. Automatic Growth Test

public class AutoInc {public static void main(String[] args){int i = 1;System.out.println("i : " + i);System.out.println("++i : " + ++i); // Pre-incrementSystem.out.println("i++ : " + i++); // Post-increment//System.out.println("i : " + i);System.out.println("--i : " + --i); // Pre-decrementSystem.out.println("i-- : " + i--); // Post-decrementSystem.out.println("i : " + i);}}

Output result:

"I: 1 ",

"++ I: 2 ",

"I ++: 2 ",

"I: 3 ",

"-- I: 2 ",

"I --: 2 ",

"I: 1"

 

 

5. Test equals

 

Class value {int I;} public class extends smethod {public static void main (string [] ARGs) {INTEGER n1 = new INTEGER (47); integer n2 = new INTEGER (47 ); system. out. println (n1.equals (N2); Value V1 = new value (); Value v2 = new value (); v1. I = v2. I = 100; // indicates pointing to the same data system. out. println (New INTEGER (v1. I ). equals (v2. I); system. out. println (v1.equals (V2 ));}}

Output result:

True

True

False

 

 

Six decimal Conversions

 public class CastingNumbers {     public static void main(String[] args){       double   above = 0.7,  below = 0.4;System.out.println("above: " + above);System.out.println("below: " + below);System.out.println("(int)above: " + (int)above);System.out.println("(int)below: " + (int)below);System.out.println("(char)('a' + above): " + (char)('a' + above));System.out.println("(char)('a' + below): " + (char)('a' + below));}}

Result:

Above: 0.7

Below: 0.4.

(INT) above: 0

(INT) below: 0

(Char) ('A' + above):

(Char) ('A' + below):

Explanation: after converting a float or double value into an integer, the fractional part is always "Cut Down"

(Instead of rounding ).

 

, Method overload

//import java.util.*;class Tree {int height;Tree() {System.out.println("Planting a seedling");height = 0;}Tree(int i) {System.out.println("Creating new Tree that is "+ i + " feet tall");height = i;}void info() {System.out.println("Tree is " + height + " feet tall");}void info(String s) {System.out.println(s + ": Tree is "+ height + " feet tall");}}public class Overload {         public static void main(String[] args) {for(int i = 0; i < 5; i++) {Tree t = new Tree(i);t.info();t.info("overloaded method");}// Overloaded constructor:new Tree();}} 
 
 
 
Explanation:

Method overloading must have the same method name and different parameters (type, order, number)

** Constructor methods and general methods can be overloaded.

Additional: Reload of the basic type

 

The basic type can be automatically upgraded from a "smaller" type to a "larger" type. This process may cause some confusion once heavy loads are involved. The following example shows how to pass the basic type to the overload method:

 

public class PrimitiveOverloading{ void f1(char x) { System.out.println("f1(char)"); }void f1(byte x) { System.out.println("f1(byte)"); }void f1(short x) { System.out.println("f1(short)");}void f1(int x) { System.out.println("f1(int)"); }void f1(long x) { System.out.println("f1(long)"); }void f1(float x) { System.out.println("f1(float)"); }void f1(double x) { System.out.println("f1(double)"); }  void f2(byte x) { System.out.println("f2(byte)"); }void f2(short x) { System.out.println("f2(short)"); }void f2(int x) { System.out.println("f2(int)"); }void f2(long x) { System.out.println("f2(long)"); }void f2(float x) { System.out.println("f2(float)"); }void f2(double x) { System.out.println("f2(double)"); }void f3(short x) { System.out.println("f3(short)"); }void f3(int x) { System.out.println("f3(int)"); }void f3(long x) { System.out.println("f3(long)"); }void f3(float x) { System.out.println("f3(float)"); }void f3(double x) { System.out.println("f3(double)"); }  void f4(int x) { System.out.println("f4(int)"); }void f4(long x) { System.out.println("f4(long)"); }void f4(float x) { System.out.println("f4(float)"); }void f4(double x) { System.out.println("f4(double)"); }  void f5(long x) { System.out.println("f5(long)"); }void f5(float x) { System.out.println("f5(float)"); }void f5(double x) { System.out.println("f5(double)"); } void f6(float x) { System.out.println("f6(float)"); }void f6(double x) { System.out.println("f6(double)"); } void f7(double x) { System.out.println("f7(double)"); } void testConstVal() {System.out.println("Testing with 5");f1(5);f2(5);f3(5);f4(5);f5(5);f6(5);f7(5); }void testChar() {char x = 'x';System.out.println("char argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);}  void testByte() {byte x = 0;System.out.println("byte argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);}  void testShort() {short x = 0;System.out.println("short argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);}void testInt() {int x = 0;System.out.println("int argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);} void testLong() {long x = 0;System.out.println("long argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);} void testFloat() {float x = 0;System.out.println("float argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);} void testDouble() {double x = 0;System.out.println("double argument:");f1(x);f2(x);f3(x);f4(x);f5(x);f6(x);f7(x);} public static void main(String[] args) {PrimitiveOverloading p = new PrimitiveOverloading();p.testConstVal();p.testChar();p.testByte();p.testShort();p.testInt();p.testLong();p.testFloat();p.testDouble();}}

 

Result:

"Testing with 5 ",

"F1 (INT )",

"F2 (INT )",

"F3 (INT )",

"F4 (INT )",

"F5 (long )",

"F6 (float )",

"F7 (double )",

"Char argument :",

"F1 (char )",

"F2 (INT )",

"F3 (INT )",

"F4 (INT )",

"F5 (long )",

"F6 (float )",

"F7 (double )",

"Byte argument :",

"F1 (byte )",

"F2 (byte )",

"F3 (short )",

"F4 (INT )",

"F5 (long )",

"F6 (float )",

"F7 (double )",

"Short argument :",

"F1 (short )",

"F2 (short )",

"F3 (short )",

"F4 (INT )",

"F5 (long )",

"F6 (float )",

"F7 (double )",

"Int argument :",

"F1 (INT )",

"F2 (INT )",

"F3 (INT )",

"F4 (INT )",

"F5 (long )",

"F6 (float )",

"F7 (double )",

"Long argument :",

"F1 (long )",

"F2 (long )",

"F3 (long )",

"F4 (long )",

"F5 (long )",

"F6 (float )",

"F7 (double )",

Float argument:

F1 (float)

F2 (float)

F3 (float)

F4 (float)

F5 (float)

F6 (float)

F7 (double)

Double argument:

F1 (double)

F2 (double)

F3 (double)

F4 (double)

F5 (double)

F6 (double)

F7 (double)

 

Explanation:

A constant is int by default.

Automatically increase by size

Float is larger than long and smaller than double.

 

8. This keyword

 public class Leaf {int i = 0;Leaf increment() {i++;return  this;}   void print(){System.out.println("i = " + i);}public static void main(String[] args){Leaf x = new Leaf();x.increment().increment().increment().print(); }}

Result: I = 3;

 

Explanation:

Because increment () returns a reference to the current object through the this keyword, it is easy

An object performs multiple operations.

 

Call the constructor In the constructor

Public class flower {int petalcount = 0; string S = new string ("null"); flower (INT petals) {petalcount = petals; system. out. println ("constructor w/INT Arg only, petalcount =" + petalcount);} flower (string SS) {system. out. println ("constructor w/string Arg only, S =" + SS); s = SS;} flower (string S, int petals) {This (petals );//! This (s); // can't call two! This. S = s; // another use of "this" system. out. println ("string & int ARGs");} flower () {This ("hi", 47); system. out. println ("default constructor (no ARGs)");} void print (){//! This (11); // not inside non-constructor! System. out. println ("petalcount =" + petalcount + "s =" + S);} public static void main (string [] Arg) {flower x = new flower (); X. print () ;}} result:

 

"Constructor w/INT Arg only, petalcount = 47 ",

"String & int ARGs ",

"Default constructor (no ARGs )",

"Petalcount = 47 s = Hi"

 

Explanation: the constructor can use the this keyword to call the difference super (inherit to call the parent class constructor)

9. Clear: end and Recycle

 

1. Objects may not be recycled.

2. Garbage collection is not equal to "analysis structure ".

3. Garbage collection is only related to memory.

 

Therefore, finalize () cannot be used as a general clearing method.

** The reason for finalize () is that when you allocate memory,

Similar to the C language rather than the Java method.

  class Book {     boolean checkedOut = false;         Book(boolean checkOut) {     checkedOut = checkOut;     }     void checkIn() {checkedOut = false;} public void finalize(){if(checkedOut)System.out.println("Error: checked out");}}  public class TerminationCondition{  public static void main(String[] args){         Book novel = new Book(true);     // Proper cleanup:   novel.checkIn();   // Drop the reference, forget to clean up:   new Book(true);// Force garbage collection & finalization:   System.gc();}} 

Result: Error: checked out

Explanation: The system forcibly clears objects in the memory.

 

 

Additional: How the garbage collector works

In some java virtual machines

Different: it is more like a conveyor belt. Every time you allocate a new object, it moves one cell forward. This means that the object storage service is empty.

The Inter-region allocation speed is very fast. Java's "heap pointer" is simply moved to an unallocated area, which is more efficient than the space allocated by C ++ on the stack.

 

 

10. Initialization

  public class InitialValues {boolean t;char c;byte b;short s;int i;long l;float f;double d;void print(String s) {          System.out.println(s);}void printInitialValues(){print("Data type Initial value");print("boolean " + t);print("char [" + c + "]");print("byte " + b);print("short " + s);print("int " + i);print("long " + l);print("float " + f);print("double " + d);}public static void main(String[] args){InitialValues iv = new InitialValues();iv.printInitialValues();}}

Result:

Data Type initial value ",

"Boolean false ",

"Char [" + (char) 0 + "]", // display a's JDK 1.6 verification under DOS

"Byte 0 ",

"Short 0 ",

"Int 0 ",

"Long 0 ",

"Float 0.0 ",

& Quot; double 0.0 & quot"

 

 

10.1 initialization sequence:

Within the class, the sequence of variable definitions determines the initialization sequence. Even if the variable definitions are scattered between the method definitions, they are still initialized before any methods (including constructors) are called. As follows;

 

 

 class Tag {Tag(int marker) {System.out.println("Tag(" + marker + ")");}}class  Card{ Tag t1 = new Tag(1);  // Before constructor static {           System.out.println("static ..");        }        Card(){// Indicate we're in the constructor:      System.out.println("Card()");      t3 = new Tag(33); // Reinitialize t3}Tag t2 = new Tag(2); // After constructorvoid f(){System.out.println("f()");}Tag t3 = new Tag(3); // At end}public class OrderOfInitialization {public static void main(String[] args) {Card t = new Card();t.f();        // Shows that construction is done}}

Result:

Static ..

"Tag (1 )",

"Tag (2 )",

"Tag (3 )",

"Card ()",

"Tag (33 )",

"F ()"

 

 

Explanation: static blocks (static binding) are defined prior to variables,

Variable definitions are initialized prior to methods (such as constructors) (dynamic binding.

 

10.2 static instance Initialization

 

class  Cup {Cup(int marker) {System.out.println("Cup(" + marker + ")");}void f(int marker) {System.out.println("f(" + marker + ")");}}class  Cups {static Cup c1;static Cup c2; static{c1 = new Cup(1);System.out.println("inside static");c2 = new Cup(2);}Cup c3 = new Cup(3);Cups(){System.out.println("Cups()");}}public class ExplicitStatic {public static void main(String[] args) {System.out.println("Inside main()");Cups.c1.f(99);   Cups.c2.f(100);new Cups();}}

Result:

Inside main ()

Cup (1)

Inside static

Cup (2)

F (99)

F (100)

Cup (3)

Cups ();

 

Explanation:

 

Static variables are initialized only once.

The data member is initialized before the constructor.

10.3 non-static instance Initialization

 

class Mug {Mug(int marker) {System.out.println("Mug(" + marker + ")");}void f(int marker) {System.out.println("f(" + marker + ")");}} public class Mugs {Mug c1;Mug c2;{c1 = new Mug(1);c2 = new Mug(2);System.out.println("c1 & c2 initialized");}Mugs(){System.out.println("Mugs()");}public static void main(String[] args) {System.out.println("Inside main()");Mugs x = new Mugs();}} 

Result:

"Inside main ()",

"Mug (1 )",

"Mug (2 )",

"C1 & C2 initialized ",

"Mugs ()"

 

Explanation: It seems like a static initialization clause, except that the static keyword is missing. This syntax is required for class initialization that supports "anonymous.

 

 

Thank you for browsing. Please be honest!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.