Java Naming Conventions

  • What Is a Naming Convention?

    A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..).

    Why Use Naming Conventions?

    Different Java programmers can have different styles and approaches to the way they program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.

    Standard Java Naming Conventions

    The below list outlines the standard Java naming conventions for each identifier type:

    Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:

     package pokeranalyzer package mycalculator

    In software companies and large projects where the packages might be imported into other classes, the names will normally be subdivided. Typically this will start with the company domain before being split into layers or features:

     package com.mycompany.utilities package org.bobscompany.application.userinterface

    Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:

     class Customer class Account

    Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:

     interface Comparable interface Enumerable

    Note that some programmers like to distinguish interfaces by beginning the name with an "I":

     interface IComparable interface IEnumerable

    Methods: Names should be in mixed case. Use verbs to describe what the method does:

     void calculateTax() string getSurname()

    Variables: Names should be in mixed case. The names should represent what the value of the variable represents:

     string firstName int orderNumber

    Only use very short names when the variables are short lived, such as in for loops:

     for (int i=0; i<20;i++) {    //i only lives in here }

    Constants: Names should be in uppercase.

     static final int DEFAULT_WIDTH static final int MAX_HEIGHT

     

    * credit to Paul Leah

מודעות פרסומת
מאת chenreuven פורסם ב-Java

Dictionary On Java

Dictionary is one of the common collection that developer can use for a lot of uses.

how to use dictionary?
1. Constructor:
function: Dictionary();
example: Dictionary dictionary = new Dictionary();
2. get value: Returns the value to which the key is mapped in this dictionary.
function: get(Object key)
example: dictionary.get("key");
3. put value: Maps the specified key to the specified value in this dictionary.
function: put(object key, objecyt value)
example: dictionary.put("key", value);
4. get all keys: Returns an enumeration of the keys in this dictionary.
function: keys();
example: Enumeration e = dictionary.key();
5. remove object: Removes the key (and its corresponding value) from this dictionary.
function: remove(Object key);
example: dictionary("key");
6. size: return int type as size of the dictionary
fucntion: size();
example: dictionary.size();
Hope u learn from this
מאת chenreuven פורסם ב-General

JSON On Java

JSON is not define as basic type on java, therefore we need to import jar file that contain the JSON type.

JAR File:  http://viralpatel.net/blogs/download/json/json-rpc-1.0.jar

To use it u must:

1. add JAR

2. import class

3. use the JSON Object

example: 

import org.json.JSONObject;

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
...
String output = json.toString();
מאת chenreuven פורסם ב-General

Stream| Files On Java

Hi All,

Here is explain&diagram about files stream that exist in java.

A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects. Some streams simply pass on data; others manipulate and transform the data in useful ways.

Reading and Writing Binary Data

InputStream/OutputStream= binary data

FileInputStream/FileOutputStream = file binary data
DataInputStream/DataOutputStream = primitive java types
ObjectOutputStream/ObjectInputStream = Object serialization

Text Input and Output

Reader/Writer = character data

InputStreamReader/OutputStreamWriter = general character reader/writer
FileReader/FileWriter = read/write character files
BufferedReader/BufferedWriter = add buffering

PrintWriter/Scanner = Formatting

Charset = encoding/decoding

מאת chenreuven פורסם ב-Java

Properties On Java

Hi All,

here is some snippt code about how to get the system properties, and also how get, set, create, clear specific property.

1. Show properties:

   java.util.Properties properties = System.getProperties();
    properties.list(System.out);

2. Get properties:

System.out.println(System.getProperty ("property name"));  

3. Set properties:

System.out.println(System.setProperty ("property name","new value"));

4. List of properties:

System property Description
java.version Java Runtime Environment version
java.vendor Java Runtime Environment vendor
java.vendor.url Java vendor URL
java.home Java installation directory
java.vm.specification.version Java Virtual Machine specification version
java.vm.specification.vendor Java Virtual Machine specification vendor
java.vm.specification.name Java Virtual Machine specification name
java.vm.version Java Virtual Machine implementation version
java.vm.vendor Java Virtual Machine implementation vendor
java.vm.name Java Virtual Machine implementation name
java.specification.version Java Runtime Environment specification version
java.specification.vendor Java Runtime Environment specification vendor
java.specification.name Java Runtime Environment specification name
java.class.version Java class format version number
java.class.path Java class path
java.library.path List of paths to search when loading libraries
java.io.tmpdir Default temp file path
java.compiler Name of JIT compiler to use
java.ext.dirs Path of extension directory or directories
os.name Operating system name
os.arch Operating system architecture
os.version Operating system version
file.separator File separator ('/' on UNIX)
path.separator Path separator (':' on UNIX)
line.separator Line separator ('\n' on UNIX)
user.name User's account name
user.home User's home directory
user.dir User's current working directory

 

מאת chenreuven פורסם ב-Java

transient" type explain"

Variables may be marked transient to indicate that they are not part of the persistent state of an object.

Example:

public class MainClass {
  public static void main(String[] argsthrows Exception {
    User a = new User("A""B");
    System.out.println("logon a = " + a);
    ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("User.out"));
    o.writeObject(a);
    o.close();

    Thread.sleep(1000)// Delay for 1 second

    ObjectInputStream in = new ObjectInputStream(new FileInputStream("User.out"));
    System.out.println("Recovering object at " new Date());
    a = (Userin.readObject();
    System.out.println("logon a = " + a);
  }

}

class User implements Serializable {
  private Date date = new Date();

  private String username;

  private transient String password;

  public User(String name, String pwd) {
    username = name;

    password = pwd;  }

  public String toString() {
    String pwd (password == null"(n/a)" password;
    return "logon info: \n   username: " + username + "\n   date: " + date + "\n   password: "
        pwd;
  }
}

Password persistance data will not transfer by stream into the file.

מאת chenreuven פורסם ב-General

Collection FrameWork and Explain

Interface                  Implemented
1. Set                           HashSet, LinkedHashSet, EnumSet
2. SortedSet                          TreeSet
3. List                          Vector, Stack, ArrayList, LinkedList
4. Queue                      PriorityQueue, LinkedList
5. Map                        Hashtable, HashMap, LinkedHashMap, WeakHashMap, IdentityHashMap
6. SortedMap                      TreeMap

Here is a little rules about collections:

1. interfaces = the abstract data types that the framework supports.
2. implementations =  the concrete versions of these interfaces.
3. algorithms= the predefined actions that can be defined on either the interfaces or their implementations, Like: Cloneable.
1. All implementations are unsynchronized.
2. All implementations are serializable and cloneable.
3. All implementations support having null elements.
מאת chenreuven פורסם ב-General

All Operators in JAVA

Hi, Here is all operator's that exist on java language:

1              ++,–        Postincrement, Postdecrement

2              ++,–        Preincrement, Predecrement

               +,-          Unary plus, unary minus

               ~            Bitwise compliment

               !            Boolean NOT

3              new          Create object

               (type)       Type cast

4              *,/,%        Multiplication, division, remainder

5              +,-          Addition, subtraction

               +            String concatenation

6              <<, >>, >>>  Left shift, right shift, unsigned right shift

7              <, <=, >, >=

               instanceof   Type comparison

8              ==, !=       Value equality and inequality

               ==, !=       Reference equality and inequality

9              &            Boolean AND

               &            Bitwise AND

10             ^            Boolean XOR

               ^            Bitwise XOR

11             |            Boolean OR

               |            Bitwise OR

12             &&           Conditional AND

13             ||           Conditional OR

14             ?:           Conditional Ternary Operator

15             =,+=,-=,     Assignment Operators

               *=,/ =,%=,

               &=,^=, |=,

               <<=, >> =,

               >>>=

מאת chenreuven פורסם ב-General

Clone: Deep Copy VS Shallow Copy

Hi, here is some explain about the difference between two operations.

I like to think of shallow/deep cloning in terms of parents and children. Shallow cloning copies the parent but shares the same children, whereas deeping cloning duplicates parents and children.

For example, if a parent A has 100 children objects, then a shallow clone would create a second parent B with references to the exact same children. In total 1 new object reference would be created. So if then modified parent A's children, parent B's children would be affected since they are shared.

With deep cloning, when I created parent B all the 100 children would also be copied. So this would amount to 101 new objects and modifying parent A's children would not affect parent B's children. Think of the performance difference between creating one object versus 101, which is why deep cloning is definitely a more expensive call.(primitives are never shared, objects are always shared in shallow cloning). [10x for Scott Selikoff ]

some example in java:

public class A {
public int i = 10;
public Object anObject;

public A() {
super();
}
public A cloneShallow() {
A a = new A();
a.i = this.i;
a.anObject = this.anObject;
return a;
}
public A cloneDeep() {
A a = new A();
a.i = this.i;
a.anObject = new Object();
// a.anObject.setParam(this.anObject.getParam());
return a;
}
מאת chenreuven פורסם ב-Java

== equal() VS

Hi, here is the differnce between to operations:

obj1.equal(obj2) :

Compares values for equality. Because this method is defined in the Object class, from which all other classes are derived, it's automatically defined for every class. However, it doesn't perform an intelligent comparison for most classes unless the class overrides it. It has been defined in a meaningful way for most Java core classes. If it's not defined for a (user) class, it behaves the same as ==.

obj1==obj2:

Compares references, not values. The use of == with object references is generally limited to the following:

  • – Comparing to see if a reference is null.
  • – Comparing two enum values. This works because there is only one object for each enum constant.
  • – You want to know if two references are to the same object
Example:
    String s1 = "CR_Dev";
    String s2 = new String(s1);    System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2)); // True, equal Values
    System.out.println(s1 + " == " + s2 + " -> " (s1 == s2)); // False, not same reference

מאת chenreuven פורסם ב-Java