Java Essentials For Newbies And Developers

Trạng thái
Chủ đề đã được đóng (không tiếp nhận thảo luận)

Joe

Thành viên VIP
21/1/13
2,969
1,310
113

Fig.1

Fig. 1 shows you the basic JAVA structure in a Computing Environment. JAVA is NOT merely an Object Oriented Programming Language or OOPL, but itself a Computing Machine (Java Virtual Machine or JVM). Hence JVM works as if it was an computer with its own Operating System or OS.
  • JVM works as if it was itself a computer and its OS is JAVA. Like a real OS JAVA supports Threading, Tasking and Memory Management (e.g. Garbage Collection, Stack/Heap Management)
  • JVM interacts with its Host OS (e.g. LINUX or WINDOWS) to share the host facilities (System and Working Paths)
  • JVM controls the IOs via its own IO technique (java.io or java.nio)
  • JVM communicates with the WEB and other Computers with its own Networking technology (java.net)
  • JVM interacts with its users via its own "Abstract Windows Tools" (java.awt) and with its own GUI technology (javax.swing and javafx) which is more up-to-date -especially JavaFX as Model-View-Controller or MVC.

I. JAVA BASICS for NEWBIES
This basic tutorial preconditions that you, as a newbie, should have the fundamental knowledge about the OS you are working with: WINDOWS or LINUX/ANDROID or iOS of Apple.


The basics of JAVA are the understanding of the System Path (SP) and Working Path (WP.) As said, JAVA is itself an OS. Therefore JAVA has its own System Path and Working Path, too. Because JAVA is a "Guest" of another OS it has to rely on and to adapt the Host-OS environment with its own SP, WP.
The System Path is the list of paths which lead to the commands and the necessary components. JAVA is usually installed, for example, in the "Program Files" directory on WINDOWS.

Host OS usually has 2 distinct paths. The SYSTEM PATH and the WORKING PATH. The SYSTEM PATH is referred as PATH and the other as "CURRENT DIRECTORY".

PATH
The OS PATH usually contains many paths which lead to the desired executable programs or commands. On WINDOWS PATH usually contains the path "c:\windows" and "c:\program files" and suppliers' subdirectories. Similar to WINDOWS LINUX PATH contains the system-relevant paths such as "/usr", "/sys", etc.

WORKING PATH
Your installed JAVA will be placed in the path, for example, "c:\program files\java". If you want to installed your JAVA in other path than this path you have to include this path into the PATH. Example: PATH=%PATH%;c:\java\jdk\bin (and similar for LINUX).
The CURRENT PATH or USER DIRECTORY is the path where you're currently work with.

Host OS and JVM always search for the given name as following:
- Firstly in the WORKING PATH
- Then in the paths included in PATH
If nothing is found error message is thrown. It's clear that the sequences in the PATH decides the access whether it is SLOW or FAST. Hence the path of the most frequently-used apps should be the "head of the queue".

CLASSPATH
As said, JAVA is in itself an OS that runs on the JVM. And the principles of OS are the PATHs like any other OS. JAVA PATH is the "CLASSPATH". The CLASSPATH contains initially all API classes (which are compressed in a JAR files and can be found in the subdirectory "../java/jdk/lib". Your own JAVA classes or JAR files must be included in this CLASSPATH. Otherwise they are missed and you get the stupid error message "Class not found". All other resources (images, data files, etc.) must be included in the Host PATH. If you forget to do that you get the same stupid error message saying the referred wasn't found. When JVM executes a JAVA app it firstly tries to load the named classes into its memory (heap/stack) by searching them in the CLASSPATH. Error is raised if one of the classes aren't found in the CLASSPATH.

WORKING WITH JAVA
Any text editor will work (e.g. "notepad".) If you're working with a "sophisticated" IDE (Integrated Development Environment) you have to be cautious about the mentioned CLASSPATH and the Host OS PATH. All the IDE relevant paths must be included to the mentioned paths accordingly. If you missed to do that your IDE won't work correctly and, worst of all, the IDE app run fine with IDE, but outside IDE it fails to run. Weird errors such as "file not found" are presented. If you work with a good Text Editor and compile the sources on a CMD-terminal (or CMD-Window) you have to include the "current directory" into the CLASSPATH so that the compiled codes could be executed by JVM. To do that the simplest way is as following (WINDOWS):
PHP:
CLASSPATH=.;%CLASSPATH%
The dot BEFORE the semicolon always indicates THIS directory (meaning current or user directory).

JAVA LANGUAGE
To access directly WINDOWS or LINUX users have to know the SHELL language and OS-commands. JAVA Language is the "SHELL" and "javac, java and some others are JAVA commands. The greatest disadvantage of IDE is that IDE shields its users from the SHELL (by suggesting APIs and Methods) and from the JVM commands.

JAVA language is an Object Oriented Programming Language (OOPL) which was based on C and influenced by C++. JAVA simplifies OOPL and disentangles some OOPL complexities: single Inheritance, strong types and standardized language structure.


JVM COMMANDS
PHP:
Command		   Description
----------------------------------------------------------------------------------------------
java			  Execute a runnable JAVA class
javaw			 Execute a runnable JAVA class in background (i.e. without occupying the CMD-
				  window)
javac			 Compile a JAVA source and produce a JAVA executable class
jar			   Java ARchiver for Java Classes
jdb			   Java Debugger
javah			 Create a C-header file for Java Native Interface (JNI)
jshell			starting the JVM Shell
Note: other JVM commands (with .exe suffix) can be found in the subdirectory../java/jdk/bin

PUBLIC, PROTECTED, PRIVATE
OOPL emphasizes the art and the way how objects and primitives should be treated. If they should be accessible by other objects they must be declared public. If they are only accessible by its "children" then they must be declared protected. If they are exclusive only by the owners they are private. Example:
PHP:
public class MyCompany {
   public String companyName;
   protected ArrayList<String> employees;
   private int counter;
   ...
}
If a class is declared protected this class is only accessible for other package members.

JAVA TYPES
If you've worked with C you'd be familiar with JAVA language. The command structure is C -meaning short, but comprehensible. All Computing Units (CU) are signed as positive or negative.
PHP:
Primitive		 Description
----------------------------------------------------------------------------------------------
boolean		   logical unit with 2 values: TRUE and FALSE. Size: 1 byte
 
byte			  the smallest CU and usually used to present an 8-bits letter. size: 1 byte
char			  16 bits CU. Size: 2 bytes and used to present human character sets
 
short			 16 bits CU. Size: 2 bytes (fixed-point number)
int			   32 bits CU. Size: 4 bytes (fixed-point number)
long			  64 bits CU. Size: 8 bytes (fixed-point number)
 
float			 32 bits CU. Size: 4 bytes (floating-point number)
double			64 bits CU. Size: 8 bytes (floating-point number)
 
String			literal of n bytes or chars (not String object)
void			  emptiness
null			  value of an uninstantiated object
----------------------------------------------------------------------------------------------
Example:
private int age;  // global
int myage;		// local (inside a method), global (outside a method)
if all global numbers are not initialized and used inside a method they have the value 0. Same for all global Objects. If uninitialized local primitive or local object is used error pops up during the compiling time.

JAVA OPERATORS
PHP:
Operator		 Description
----------------------------------------------------------------------------------------------
+				math. addition or logical appending
-				math. subtraction
*				math. multiplication
/				math. division
,				continuation
;				end of an expression
=				assignment
:				increment by 1 till end by "for"
!				not (invert of a boolean value)
==			   "physical" equal by object, logical equal by primitives
!=			   "physical" unequal by object, logical unequal by primitives
>=			   logical greater or equal
<=			   logical less or equal
<<			   arith. shift-left
>>			   arith. shift-right
->			   Lambda-Expression
[ ]			  Array declaration
( )			  parameter declaration (empty for no parameter)
{ }			  Expression Block
...			  another form of []
?				template for unknown type of object
< >			  type-requirement for an object
Example:
PHP:
int a = 10, b = 20;		  // continuation int for b end of expression
int c = a << 2;			  // 2x shift-left of a then assigns the result to c
ArrayList<String> al;		// ArrayList of type String
String[] s;				  // String Array s of unknown number of elements
String x[10];				// String Array x of 10 elements
String S = "Joe" + "Nartca"; // append Nartca to Joe and assign the result to S
String joe = "Joe";		  // primitive or literal
String O = new String("Joe");// object
joe == "Joe";				// TRUE because joe is a primitive and "Joe" is a literal (=primitive)
O   == "Joe";				// FALSE because the "physical" of both are physical unequal
for (String x : X) ...	   // same for (int i = 0; i < X.length; ++i) { String x = X[i]; ... }
JAVA BLOCK
A JAVA block is a group of JAVA expressions and data (i.e. variables). A block can be either a class itself, or a method, or a lambda expression. A JAVA block always starts with an open Curly Bracket { and ends with a close Curly Bracket }. Example
PHP:
public class MyClass { // Class/object block
  ...
  public int math(int a, int b, char op) {  // method block
	 switch (op) { // group of Expressions block
	   case '+': return a+b;
	   case '-': return a-b;
	   case '*': return a*b;
	   case '/': if (b != 0) return a/b;
				 throw new Exception("divisor is 0");
	   default: System.out.println("Unknown Operation: '+"op+"'");
	 } // end of group of Expressions block
	 return 0;
  } // end of method block
} // end of Class/object block
MUTABLE AND IMMUTABLE
If an object cannot be modified this object is an IMMUTABLE object. String is for example an immutable object. If an immutable object must be modified the old is discarded and a new one is created under this name. Otherwise this object is MUTABLE -meaning: it can be modified. Example:
PHP:
String myName = new String("Joe Nartca"); // immutable String object
String cdj = "Congdongjava";			  // immutable String literal (or primitive)
StringBuffer joe = new StringBuffer("Joe Nartca"); // mutable object
 
myName = myName.replace("e N", "e T. N"); // old object was discarded, new object was created
										  // with the content Joe T. Nartca
 
joe.replace(2, 4, "e T. N");   // 3 characters "e N" of joe were replaced with "e T. N" and the new
							   // content is "Joe T. Nartca". Object joe stays the same
OBJECT
Beside the primitives JAVA OOPL also works with complex structures which combines executable codes and data of any type or other structure. The complex structure is called Object (in the old fashion: struct in C, for example). Simple form (like C "struct") has the acronym "POJO" or "Plain Old Java Object". A JAVA object is declared by the keyword class
PHP:
public class This_is_an_Object {
   ...
}
The codes of an object are arranged and structured in several groups to do some certain work. The "group" is called METHOD (in the old fashion: a function is when it returns a result (primitive or object), otherwise it's a procedure -meaning it returns a void).

Data which could be some primitives or other JAVA objects are the variables a JAVA object works with. Data within a METHOD is the LOCAL variables (or data). Local variables are inaccessible by other methods. Variables outside all methods are GLOBAL data and can be accessed by all methods. Accessing local data is always faster and more efficient than accessing any global data. A good developer won't waste with global data if he mustn't.

THREAD AND TASK
First of all: a process is a "working procedure unit" that produces a predetermined result. Thread and Task are independent processes which are only different from the environment how they work with. Thread shares the environment of its parents while Task doesn't. Shared objects and variables (of threads) must be synchronized between each others. Therefore working with threads is more sensitive and complicated than working with tasks. Btw., a Thread could be seen as a simplified or a lightweight Task. In the Advanced Sessions I show you how to work with threads and tasks.

JAVA thread is always an extension of Object class Thread or an implementation of the Runnable interface.

JAVA task is usually an implementation of the Callable interface in combination with the "bearer" Object class FutureTask and usually in use with the special JAVA service ExecutorService.

SINGLE INHERITANCE
Inheritance
is the core of an OOPL. If an object which is "extended" and shared the structures (methods and data) of its parents is called child object and the shared part are the inheritance. Too many "parents" like in C++ could lead to entangling of clarity (e.g. which parents of a certain method/object when all parents have the same method /object name?). To avoid this complicated inheritance all JAVA objects are children of ONE parents (Object). And each derived object can only have ONE derived parents. Example: Object JPanel
PHP:
java.lang.Object					  // ancestor
   java.awt.Component				 // son
	 java.awt.Container			   // grandson
	   javax.swing.JComponent		 // grand-grandson
		 javax.swing.JPanel		   // grand-grand-grandson
If you want to individualize a JPanel you derive your object from JPanel, but you cannot derive from Jpanel AND JFrame (double inheritances). To do that you use the keyword extends
PHP:
public class MyPanel extends JPanel {
  ...
}
For the case that you do need "more" functional solutions which won't exist in the desired object JAVA offers you a leeway called "INTERFACE". With the interfaces you can "expand" your individualized object as far as you could. The keyword for that is "implements". Example:
PHP:
public class MyPanel extends JPanel implements ActionListener, MouseListener {
  ...
}
With the interfaces to "ActionListener" and "MouseListener" you need only to IMPLEMENT (hence the keyword) the required methods with your wished functionality. Single Inheritance with 2 leeway to ActionListener and MouseListener. That's is the reason why JAVA is so superior.

STATIC, VOLATILE, SERIALIZABLE, TRANSIENT
When something is immobile, fixed and invariable it's STATIC. A static object or primitive is in JAVA like a constant that stays forever "fixed" in JVM memory. Hence static objects and data are "heavy" like stones in Memory and shouldn't be used exaggeratedly. A JAVA app is started by the method static void main() by common Java or static void launch() by JavaFX (or with the implemented start() of JavaFX-Application object).
By objects or data that are declared VOLATILE JVM (and compiler) always reads their value from main memory and follow happens-before relationship on visibility of volatile variable among the threads. If you aren't sure with VOLATILE variables you should avoid using them and rather work with synchronization (keyword synchronized).
Object that is implemented with the interface Serializable (which hasn't any method needed to be implemented) can be saved (written). And its "frozen" state of its data can be retrieved (read) and reused. However, data or objects that are declared "TRANSIENT" won't be saved in this case and their state gets lost. Example:
PHP:
public class MyObject implements Serializabe {
   private static final long SerialVersionUID = 100l;
   private volatile int i = 0;
   private transient
   public String name;
   public String address;
   private transient String password;
   public int number;
   ...
}
 
Sửa lần cuối:

Joe

Thành viên VIP
21/1/13
2,969
1,310
113
Dear all,
Poll is closed. Only ONE member showed his/her interest. it seems that most of other Congdongjava members are good with Java and won't need any further tutorial. Thank you all for your participation. Thread is closed.
Joe
 
Trạng thái
Chủ đề đã được đóng (không tiếp nhận thảo luận)