Register Login





|

Top Links: >> 80. Technology >> Internet Technology Summit Program >> 1. Java Introduction
Current Topic: 1.2.4. Java Style and Terms
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
When your future employer will look at your source, the first thing that is well visible is your coding style. If you keep basic Java style features - your code looks good. Keep in mind that logical errors are not usually visible till code is running. But the style is very visible.

Below is a sample of code provided with the idea to illustrate Java style and terms.

Take your time to read, learn, and keep good style habits.

// StyleExample

// The package name usually includes a company name. In this case "its" represents Internet Technology Systems company
package its.examples; // Internet Technology System packages

import its.gis.ITShape;
import its.util.Tree;

/** The class usually starts with the header-description.

"/**" - this beginning will be recognized by JavaDoc tool and the JavaDoc will produce web pages of online documentation.

* A class implementing Java Style Example.
* The purpose of the class is to provide Java style samples
* How to use this class: ...
* Example: (It is a good idea to include a sample or two of the usage - you will do this later...)

* @version 0.1 September 10, 1996
* @author Jeff.Zhuk@JavaSchool.com
*/

public class StyleExample extends ITShape {
// class data members
private Tree[] dataTree; // array of objects
// .. More data ?
// class methods with JavaDoc headers
/** Every header starts with "/**" and ends with "*/".
* The header is not used to compile code, just to produce documentation.
* Below we describe the method getDataTree()
* The description not only serves for documentation; it is also our plan of coding.
* after the header we provide the code, which implements the plan.

* getDataTree(int iIndex) method returns one element of array
* @param iIndex element index in the dataTree[] array
* @return dataTree if available, return null in other cases
*/
public Tree getDataTree(int iIndex) {
if(iIndex < 0 || dataTree == null || dataTree.length < iIndex) { // check first!
return null; // to prevent run-time exceptions
}
return dataTree[iIndex];
}
// more methods ...
} // end of StyleExample class



Java style recommendations:

Provide full JavaDoc comments on all classes, methods, and interfaces.
Comments should include clear descriptions, examples of usages, parameters,
return values, and exception tags if needed.

Use blocks in if-else, switch, and all looping constructs, such as for loop that will be discussed later. This makes alterations fail-safe.
All cases and defaults in the switch should have break statements for the same reason.

Use:

String s = "hello"; // instead of String s = new String("hello");


Do not use "try-catch" blocks to prevent run-time exceptions, but always use a proper logic instead
(see above checking on index and not-null value of the dataTree parameter).

Java Basic Terms

Java Class, Data, Constructor and Methods
Writing a program in Java means writing classes.
What is a class? A class is a user-defined data structure with the methods that manage the data.

Sometimes we talk about object properties or class variables; this is all the same. We still talk about data. When a program creates a new object of a class (instantiate an object) it usually calls a constructor, which allocates memory for data... unless data are not defined as static.

Static data will not be multiplied with every object defined. They are just allocated once as part of a class definition and can be used in the Singleton design patterns, when a program needs a single object shared by many users. We will talk more about static data later on.

What is a constructor?
The constructor is a very special method that constructs an object of a specific type.
For example, to create an object of a type Cat we type:
Cat c = new Cat();
We used here a default constructor, Cat(), which has no parameters.
This constructor makes space for the object, in other words it allocates memory, so we later can set some values in this memory.
Default constructor is defined by Java for us. We do not need to define it in our source.
We can define a specific constructor which can create an object and immediately set some values.
For example, the cat with the name "Bingo". Cat c = new Cat("Bingo");
But usually to set values and to get values we use methods.

What is a method? Sometimes called a function or a message, a method describes object behavior. An instance of a class can invoke a method to change or retrieve data.

This is an example of a class (Cat) definition with data (color) and get and set methods:


// class is defined as public to provide public access to the class
// The name of the class must start with a capital letter according to Java language recommendations
public class Cat {
// data
private String color; // keep data private
// methods, made public to allow access to data via the methods
public void setColor(String color) { // setting data
this.color = color; // assign class data, color, (this.color) to the argument, color
}
public String getColor() { // getting data
return color;
}
// The main will test class methods
// The main method is static, so it can be called directly without creating an object
// The main method signature must be exactly like below:
// public static void main(String[] args) including an array of strings that could be passed as parameters
public static void main(String[] args) {
// Creating an object of the class by calling a constructor with new Cat()
Cat myCat = new Cat();
// Type in Eclipse myCat and then enter the dot.
// See how Eclipse gives away all methods that this object can perform, just select a proper one
myCat.setColor("black"); // setting a color to black
// Now, let us test the getColor method
String catColor = myCat.getColor(); // assigning the color to the variable catColor
// display the result with System.out.println
System.out.println("catColor="+catColor); // check the Console window to see the result
} // end of the main method
} // end of class
Was it clear so far? Highlight the text in question Or


Let us talk about two important Java keywords: final and static.
What is the difference between final and static?
Final means not changeable. A final class cannot be extended with a subclass, a final method cannot be overridden and a final variable cannot change its initialized value.
For example:


public final class Banker { // this class cannot have subclasses
private final int maxAge = 125; // the variable maxAge cannot be changed in a program


Static variables or methods are associated with a particular class as a whole--not with particular instances of the class.
For example:


public class IOMaster {
/**
* The method readTextFile()
* This method can be called without creating an object of the class IOMaster, just by referencing the class name
* We do not need to create an object of IOMaster calss; we just immediately call the method with the class name.
* Example:
String text = IOMaster.readTextFile("c:/ITS/resources/myTextFile.txt");
* The method readTextFile() requires a parameter of a filename to read; The next line uses the @param keyword of JavaDoc
* The method returns a String - text of the file, which the method reads. The following line uses the @return keyword of JavaDoc
* @param filename
* @return text
*/
public static String readTextFile(String filename) {
//...
}


Those are just samples of the Java style, not complete classes. Do not try to place it in Eclipse, they will raise red flags.
You will create real code as assignments in other lessons.

Another Java term, which we learn today is type casting
Converting from data type to another data type is called type casting.

Type casting is used when dealing with different data types.

There are two types of casting:
Implicit Casting
Explicit Casting

Implicit casting, when Java does it automatically for us


double d = 3; // type widening from 4 bytes (int) to 8 bytes (double)


Explicit casting, when we precisely tell Java what to do by providing specific cast, such as (int) in the samples below


int i = (int)3.0; // type narrowing from 8 bytes (double) to 4 bytes (int)
int i = (int)3.9; // Fraction part is truncated while transforming from 8 bytes (double) to 4 bytes (int)


In both cases the result is 3. There is no rounding that occurs during the casting process.

One more thing that helps your code in Eclipse.
Use this shortcut key in Eclipse to better format your sources: CTRL/SHIFT/F
and
Check this link for more Eclipse shortcut keys: https://dzone.com/articles/top-30-eclipse-keyboard-shortcuts-for-java-program-1


Assignments:

a) Google and read about Java methods and parameters
b) Read more on Java Terms here
c) Create in Eclipse under the day2 package the Cat class (not copy/paste, but type it looking into these notes) and another class that you would find in the process of this Google search.
Select a very small class, type and run it in Eclipse.
d) Change this example to reflect Java Style recommendations and run it again. The changes you provided should not change the part executed by a machine, but should make this class be better readable and understandable by you and other programmers.
e) Search Google and Youtube for the best presentations on JavaDoc, Java Style, Java Terminology, read, watch, select and email 2 best links for each subject to dean@ituniversity.us

Recommended (optional) materials:
http://www.leepoint.net and http://chortle.ccsu.edu/cs151/cs151java.html
Links recommended by students:
https://google.github.io/styleguide/javaguide.html
https://www.youtube.com/watch?v=6XoVf4x-tag
https://www.youtube.com/watch?v=Ue3l9QHh_Mw
https://www.bing.com/videos/search?q=java+terminology&&view=detail&mid=58CEADE013AE55F3409358CEADE013AE55F34093&FORM=VRDGAR

https://www.bing.com/videos/search?q=javadoc&&view=detail&mid=9D9A0C87A9B0A68218F29D9A0C87A9B0A68218F2&FORM=VRDGAR
Questions and Answers (QnA): QnA1 | QnA2 | QnA3 | QnA4 | QnA5 | QnA6 | QnA7 | QnA8 | QnA9
We offer a fun way to share your experience and be rewarded.
You create a puzzle - quiz with a good question and several answers, one correct and several wrong ones.
The question as well as answers can include text, links, video.
This is your creation, completely up to your taste, humor, and of course your knowledge.
If there is an existing quiz above, you need first to solve the puzzles and evaluate the quality (at the bottom of every quiz).
After finishing the existing quiz you will be able to create your own. The best puzzles will be rewarded!
We invite you to create your own questions and answers (QnA) to increase your rank and win the Top Creativity Prize!

Topic Graph | Check Your Progress | Propose QnA | Have a question or comments for open discussion?
<br/>// StyleExample  
<br/> 
<br/>// The package name usually includes a company name. In this case "its" represents Internet Technology Systems company
<br/>package its.examples; // Internet Technology System packages
<br/> 
<br/>import its.gis.ITShape;
<br/>import its.util.Tree;
<br/>  
<br/>/**  The class usually starts with the header-description.
<br/>
<br/>"/**" - this beginning will be recognized by JavaDoc tool and the JavaDoc will produce web pages of online documentation.
<br/>
<br/> * A class implementing Java Style Example.  
<br/> * The purpose of the class is to provide Java style samples
<br/> * How to use this class: ...  
<br/> * Example: (It is a good idea to include a sample or two of the usage - you will do this later...)
<br/>
<br/> * @version 0.1 September 10, 1996 
<br/> * @author Jeff.Zhuk@JavaSchool.com 
<br/> */  
<br/> 
<br/>public class StyleExample extends ITShape { 
<br/>    // class data members
<br/>    private Tree[] dataTree;  // array of objects
<br/>    // .. More data ?
<br/>    // class methods with JavaDoc headers  
<br/>/** Every header starts with "/**" and ends with "*/". 
<br/> * The header is not used to compile code, just to produce documentation.
<br/> * Below we describe the method getDataTree()
<br/> * The description not only serves for documentation; it is also our plan of coding.
<br/> * after the header we provide the code, which implements the plan.
<br/>
<br/> * getDataTree(int iIndex) method returns one element of array 
<br/> * @param iIndex element index in the dataTree[] array 
<br/> * @return dataTree if available, return null in other cases 
<br/> */ 
<br/>    public Tree getDataTree(int iIndex) {
<br/>        if(iIndex < 0 || dataTree == null || dataTree.length < iIndex) { // check first!
<br/>            return null;  // to prevent run-time exceptions 
<br/>        }
<br/>        return dataTree[iIndex]; 
<br/>    }
<br/>    // more methods ...    
<br/>} // end of StyleExample class 
<br/>



Java style recommendations:

Provide full JavaDoc comments on all classes, methods, and interfaces.
Comments should include clear descriptions, examples of usages, parameters,
return values, and exception tags if needed.

Use blocks in if-else, switch, and all looping constructs, such as for loop that will be discussed later. This makes alterations fail-safe.
All cases and defaults in the switch should have break statements for the same reason.

Use:

String s = "hello"; // instead of String s = new String("hello");


Do not use "try-catch" blocks to prevent run-time exceptions, but always use a proper logic instead
(see above checking on index and not-null value of the dataTree parameter).

Java Basic Terms

Java Class, Data, Constructor and Methods
Writing a program in Java means writing classes.
What is a class? A class is a user-defined data structure with the methods that manage the data.

Sometimes we talk about object properties or class variables; this is all the same. We still talk about data. When a program creates a new object of a class (instantiate an object) it usually calls a constructor, which allocates memory for data... unless data are not defined as static.

Static data will not be multiplied with every object defined. They are just allocated once as part of a class definition and can be used in the Singleton design patterns, when a program needs a single object shared by many users. We will talk more about static data later on.

What is a constructor?
The constructor is a very special method that constructs an object of a specific type.
For example, to create an object of a type Cat we type:
Cat c = new Cat();
We used here a default constructor, Cat(), which has no parameters.
This constructor makes space for the object, in other words it allocates memory, so we later can set some values in this memory.
Default constructor is defined by Java for us. We do not need to define it in our source.
We can define a specific constructor which can create an object and immediately set some values.
For example, the cat with the name "Bingo". Cat c = new Cat("Bingo");
But usually to set values and to get values we use methods.

What is a method? Sometimes called a function or a message, a method describes object behavior. An instance of a class can invoke a method to change or retrieve data.

This is an example of a class (Cat) definition with data (color) and get and set methods:

<br/>// class is defined as <b>public</b> to provide public access to the class
<br/>// The name of the class must start with a capital letter according to Java language recommendations
<br/>public class Cat {
<br/> // data
<br/> private String color; // keep data private
<br/> // methods, made public to allow access to data via the methods
<br/> public void setColor(String color) { // setting data
<br/>   this.color = color; // assign class data, color, (this.color) to the argument, color
<br/> }
<br/> public String getColor() { // getting data
<br/>   return color; 
<br/> }  
<br/> // The <b>main</b> will test class methods
<br/> // The main method is static, so it can be called directly without creating an object
<br/> // The main method signature must be exactly like below: 
<br/> // <b>public static void main(String[] args)</b> including an array of strings that could be passed as parameters
<br/> public static void main(String[] args) {
<br/>   // Creating an object of the class by calling a constructor with <b>new Cat()</b>
<br/>   Cat myCat = new Cat();
<br/>   // Type in Eclipse <b>myCat</b> and then enter the dot.
<br/>   // See how Eclipse gives away all methods that this object can perform, just select a proper one
<br/>   myCat.setColor("black"); // setting a color to black
<br/>   // Now, let us test the getColor method
<br/>   String catColor = myCat.getColor(); // assigning the color to the variable catColor
<br/>   // display the result with System.out.println
<br/>   System.out.println("catColor="+catColor); // check the Console window to see the result
<br/> } // end of the main method
<br/>} // end of class
<br/>






Was it clear so far? Highlight the text in question

Or



Let us talk about two important Java keywords: final and static.
What is the difference between final and static?
Final means not changeable. A final class cannot be extended with a subclass, a final method cannot be overridden and a final variable cannot change its initialized value.
For example:

<br/>public final class Banker { // this class cannot have subclasses
<br/>private final int maxAge = 125; // the variable maxAge cannot be changed in a program
<br/>


Static variables or methods are associated with a particular class as a whole--not with particular instances of the class.
For example:

<br/>public class IOMaster {
<br/>/**
<br/> * The method readTextFile()
<br/> * This method can be called without creating an object of the class IOMaster, just by referencing the class name
<br/> * We do not need to create an object of IOMaster calss; we just immediately call the method with the class name.
<br/> * Example: 
<br/>String text = IOMaster.readTextFile("c:/ITS/resources/myTextFile.txt");
<br/> * The method readTextFile() requires a parameter of a filename to read; The next line uses the @param keyword of JavaDoc 
<br/> * The method returns a String - text of the file, which the method reads. The following line uses the @return keyword of JavaDoc
<br/> * @param filename
<br/> * @return text
<br/> */
<br/>public static String readTextFile(String filename) { 
<br/>//...
<br/>}
<br/>


Those are just samples of the Java style, not complete classes. Do not try to place it in Eclipse, they will raise red flags.
You will create real code as assignments in other lessons.

Another Java term, which we learn today is type casting
Converting from data type to another data type is called type casting.

Type casting is used when dealing with different data types.

There are two types of casting:
Implicit Casting
Explicit Casting

Implicit casting, when Java does it automatically for us

<br/>double d = 3; // type widening from 4 bytes (int) to 8 bytes (double)
<br/>


Explicit casting, when we precisely tell Java what to do by providing specific cast, such as (int) in the samples below

<br/>int i = (int)3.0; // type narrowing from 8 bytes (double) to 4 bytes (int)
<br/>int i = (int)3.9; // Fraction part is truncated while transforming from 8 bytes (double) to 4 bytes (int)
<br/>


In both cases the result is 3. There is no rounding that occurs during the casting process.

One more thing that helps your code in Eclipse.
Use this shortcut key in Eclipse to better format your sources: CTRL/SHIFT/F
and
Check this link for more Eclipse shortcut keys: https://dzone.com/articles/top-30-eclipse-keyboard-shortcuts-for-java-program-1


Assignments:

a) Google and read about Java methods and parameters
b) Read more on Java Terms here
c) Create in Eclipse under the day2 package the Cat class (not copy/paste, but type it looking into these notes) and another class that you would find in the process of this Google search.
Select a very small class, type and run it in Eclipse.
d) Change this example to reflect Java Style recommendations and run it again. The changes you provided should not change the part executed by a machine, but should make this class be better readable and understandable by you and other programmers.
e) Search Google and Youtube for the best presentations on JavaDoc, Java Style, Java Terminology, read, watch, select and email 2 best links for each subject to dean@ituniversity.us

Recommended (optional) materials:
http://www.leepoint.net and http://chortle.ccsu.edu/cs151/cs151java.html
Links recommended by students:
https://google.github.io/styleguide/javaguide.html
https://www.youtube.com/watch?v=6XoVf4x-tag
https://www.youtube.com/watch?v=Ue3l9QHh_Mw
https://www.bing.com/videos/search?q=java+terminology&&view=detail&mid=58CEADE013AE55F3409358CEADE013AE55F34093&FORM=VRDGAR

https://www.bing.com/videos/search?q=javadoc&&view=detail&mid=9D9A0C87A9B0A68218F29D9A0C87A9B0A68218F2&FORM=VRDGAR
Questions and Answers (QnA): QnA1 | QnA2 | QnA3 | QnA4 | QnA5 | QnA6 | QnA7 | QnA8 | QnA9

We offer a fun way to share your experience and be rewarded.
You create a puzzle - quiz with a good question and several answers, one correct and several wrong ones.
The question as well as answers can include text, links, video.
This is your creation, completely up to your taste, humor, and of course your knowledge.
If there is an existing quiz above, you need first to solve the puzzles and evaluate the quality (at the bottom of every quiz).
After finishing the existing quiz you will be able to create your own. The best puzzles will be rewarded!

We invite you to create your own questions and answers (QnA) to increase your rank and win the Top Creativity Prize!



Have a suggestion? - shoot an email
Looking for something special? - Talk to AI
Read: IT of the future: AI and Semantic Cloud Architecture | Fixing Education
Do you want to move from theory to practice and become a magician? Learn and work with us at Internet Technology University (ITU) - JavaSchool.com.

Technology that we offer and How this works: English | Spanish | Russian | French

Internet Technology University | JavaSchool.com | Copyrights © Since 1997 | All Rights Reserved
Patents: US10956676, US7032006, US7774751, US7966093, US8051026, US8863234
Including conversational semantic decision support systems (CSDS) and bringing us closer to The message from 2040
Privacy Policy