I.T. Discussion Community!
-Collapse +Expand
Java
Search Java Group:

Advanced
-Collapse +Expand Java To/From
To/FromCODEGuides
-Collapse +Expand Java Store
PRESTWOODSTORE

Prestwood eMagazine

September Edition
Subscribe now! It's Free!
Enter your email:

   ► KBJava Knowledge Base  Print This    Code Snippet DB All Groups  

Java Code Snippets Page

These Code Snippets are contributed by you (our online community members). They are organized by our knowledge base topics. Specifically, by the Java sub-topics.

Contribute a Code Snippet
Expand All

32 Java Code Snippets

Group: Java


Topic: Java

-Collapse +Expand 1. Java Abstraction (abstract)
 

Java supports marking a full class as abstract as well as class members. A subclass must either implement the abstract members or you must declare the subclass abstract (which delays the implementation to it's subclass).

public abstract class Dog {
  abstract void Bark();
}
Posted By Mike Prestwood, Post #101487, KB Topic: Java
-Collapse +Expand 2. Java Case Sensitivity (Yes)
 

Java is case sensitive.

Customary casing:

  • Classes - Initial Caps (Pascal Casing)
  • Variables - Initial lowecase (Camel case)
  • Methods - Initial lowecase (Camel case)
Posted By Mike Prestwood, Post #101338, KB Topic: Java
-Collapse +Expand 3. Java Comparison Operators (==, !=)
 

The Java comparison operators are:

  • < less than
  • <= less than or equal to
  • == equal to
  • >= greater than or equal to
  • > greater than
  • != not equal
Posted By Mike Prestwood, Post #101815, KB Topic: Java
-Collapse +Expand 4. Java Exception Trapping (try/catch/finally)
 

Languages Focus: Exception Trapping

A common usage of exception handling is to obtain and use resources in a "try-it" block, deal with any exceptions in an "exceptions" block, and release the resources in some kind of "final" block which executes whether or not any exceptions are trapped.

Java Exception Trapping

try {
  /* Risky code here. */
}
catch (SomeException) {        //one or more.
  /* Recovery here. */
}
finally {                      //0 or one.
  /* Do something. */
}
Posted By Mike Prestwood, Post #101366, KB Topic: Java
-Collapse +Expand 5. Java File Extensions (.java)
 

The customary primary source file extension for Java code is ".java" which could contain anywhere from a single class to the entire source code.

Other important files:

  • .JAR - Java archive file (compressed code file). Archive that contains multiple Java files and is compressed using .ZIP compression; stores Java classes and metadata and may be digitally signed; runs as a program if the Java Runtime Environment (JRE) is installed on the computer.
  • .CLASS - compiled source code which are platform-independent. If a source file has more than one class, each class is compiled into a separate .class file. These .class files can be loaded by any Java Virtual Machine (JVM).
Posted By Mike Prestwood, Post #101351, KB Topic: Java
-Collapse +Expand 6. Java Static Members (static)
 

When calling a static method from within the same class, you don't need to specify the class name.

class MyUtils {
//Static method.
  public static void MyStaticMethod() {
}
}
Posted By Mike Prestwood, Post #101478, KB Topic: Java



Topic: Tool Basics

-Collapse +Expand 7. Java Code Blocks ({ })
 

Curly braces are used to bracket code blocks including classes and the methods within a class.

For Java, JavaScript, PHP, and C++, I prefer to put the first { at the end of the first line of the code block as in the example above because I see moreJava codeformatted that way.

public class Dog {
  public bark() {
    System.out.println("Ruff");
  }
}
Posted By Mike Prestwood, Post #101416, KB Topic: Tool Basics
-Collapse +Expand 8. Java Comments (// or /* ... */)
 

Commenting Code
Java uses "//" for a single line comment and /* */ for a multiple line comment.

//Single line comment in MS (not ANSI compliant so do NOT use).
/* ANSI compliant single line comment. */
/*
Multiple line
comment.
*/
/*
* This is another popular way 
* to write multi-line comments.
*/
Posted By Mike Prestwood, Post #101503, KB Topic: Tool Basics
-Collapse +Expand 9. Java Deployment Overview
 

Java applets and applications both require the Java Runtime Environment (JRE) and any additional dependencies you've added.

Posted By Mike Prestwood, Post #101931, KB Topic: Tool Basics
-Collapse +Expand 10. Java Development Tools
 

Languages Focus: Development Tools

Primary development tool(s) used to develop and debug code.

Java Development Tools

Many compilers and development tools are available. Common development tools include Sun's J2EE, CodeGear JBuilder, and Eclipse.

Posted By Mike Prestwood, Post #101548, KB Topic: Tool Basics
-Collapse +Expand 11. Java Literals (quote)
 

Literals are quoted as in "Prestwood". If you need to embed a quote use a slash in front of the quote as in \".

System.out.println("Hello");
System.out.println("Hello \"Mike\".");
  
//Does Java evaluate this simple
//floating point math correctly? No!
if ((.1 + .1 + .1) == 0.3) {
System.out.println("Correct");
} else {
System.out.println("Not correct");
}
Posted By Mike Prestwood, Post #101521, KB Topic: Tool Basics
-Collapse +Expand 12. Java Overview and History
 

Promoted as a single source cross-platform runtime system (Write Once, Run Anywhere). Java builds on and in some ways simplifies the object oriented features of C++. Java applications are typically compiled to byte-code and can run on any platform running the Java Virtual Machine (JVM).

Target Platforms: Java is suitable for creating many types of cross-platform applications that target the JVM including desktop business applications.

Posted By Mike Prestwood, Post #101720, KB Topic: Tool Basics
-Collapse +Expand 13. Java Report Tools Overview
 

Both Eclipse 3.3 and JBuilder 2008 come bundled with Business Intelligence and Reporting Tools (BIRT). BIRT is an Eclipse-based open source reporting system with both a report designer based on Eclipse, and a runtime component that you can add to your app server plus a charting engine that lets you add charts.

Posted By Mike Prestwood, Post #101901, KB Topic: Tool Basics
-Collapse +Expand 14. Java String Concatenation (+ or append)
 

Java String Concatenation

In Java, you use either the String concatenation + operator or StringBulder class methods such as append. Since Java compilers frequently create intermediate objects when the + operator is used and don't when StringBuilder.append is used, the append method is faster than the + operator.

In general, use the convenience of a + operator when speed is not an issue. For example, when concatenating a small number of items and when code isn't executed very frequently. A decent rule of thumb is to use the + operator for general purpose programming and then optimize the + operator with StringBuilder.append as needed.

Simple + operator example:

System.out.println("Hello" + " " + "Mike.");

 

Using StringBuilder example:

StringBuilder myMsg = new StringBuilder();

myMsg.append("Hello ");
myMsg.append("Mike.");
 
System.out.println(myMsg);
Posted By Mike Prestwood, Post #101619, KB Topic: Tool Basics
-Collapse +Expand 15. Java Unary Operators
 

An operation with only one operand (a single input). The Java unary operators are ++, --, +, -, ~, and !.

  • + Indicates positive value (numbers are positive without this)
  • - Negates an expression
  • ++ Increment operator by 1
  • -- Decrement operator by 1
  • ! Logical complement operator (inverts the value of a boolean)
  • ~ Bitwise inversion operator (works on integral data types)
Posted By Mike Prestwood, Post #101557, KB Topic: Tool Basics
-Collapse +Expand 16. Java Variables (int x = 0;)
 

Variable names are case sensitive.

The Java basic types are boolean, byte, short, int, long, float, double, and char. You can also declare a variable to hold a particular instance of a class such as String.

C++, Java, and C# all use C-like variable declaration.

int a;
int a, b;
int age = 43;
String FullName;
Posted By Mike Prestwood, Post #101578, KB Topic: Tool Basics



Topic: Language Basics

-Collapse +Expand 17. Java If Statement (if..else if..else)
 

Syntax template:

if (expression) {
  expression1_true_code;
} else if (expression2) {
  expression2_true_code;
} else {
  otherwise_code;
}
if ((.1 + .1 + .1) == 0.3) {
  System.out.println("Correct");
} else {
  System.out.println("Not correct");
}
Posted By Mike Prestwood, Post #101816, KB Topic: Language Basics
-Collapse +Expand 18. Java Logical Operators
 

Java logical operators:

&& and, as in this and that
|| or, as in this or that
! Not, as in Not This
& boolean logical OR (not short circuited)
| boolean logical OR (not short circuited)
?: Ternary (short for if-then-else)
~ Unary bitwise complement
<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
^ Bitwise exclusiv OR

//Given expressions a, b, c, and d:
if !((a && b) && (c || d)) {
  //Do something.
}
Posted By Mike Prestwood, Post #101885, KB Topic: Language Basics



Topic: Language Details

-Collapse +Expand 19. Associative Arrays in Java (a Map)
 

An associative array links a set of keys to a set of values. In Java, associative arrays are implemented as Maps.

This will print "Arizona."

import java.util.*;

public class Maps
{
    public static void main(String[] args)
    {
        Map states = new HashMap();
       
        states.put("CA", "California");
        states.put("FL", "Florida");
        states.put("AZ", "Arizona");

        System.out.println(states.get("AZ"));
    }
}
Posted By Stephen Berry, Post #101221, KB Topic: Language Details
-Collapse +Expand 20. Java Associative Array (HashMap())
 

An associative array links a set of keys to a set of values. In Java, associative arrays are implemented as Maps.

This will print "Arizona."

import java.util.*;

public class Maps
{
    public static void main(String[] args)
    {
        Map states = new HashMap();
       
        states.put("CA", "California");
        states.put("FL", "Florida");
        states.put("AZ", "Arizona");

        System.out.println(states.get("AZ"));
    }
}
Posted By Mike Prestwood, Post #101515, KB Topic: Language Details
-Collapse +Expand 21. Java Class..Object (class..new)
 

Unlike languages such as C++ and Object Pascal, every line of code written in Java must occur within a class.

//Declare class.
public class Cyborg {
  //Fields.
  private String cyborgName;
  private int age;
 
  //Constructor.
  public Person() {
  cyborgName = "unknown";
  age = 0;
  }
}
//Create object from class.
Cyborg p = new Cyborg();
p.getClass(); //From the Object base class.
Posted By Mike Prestwood, Post #101401, KB Topic: Language Details
-Collapse +Expand 22. Java Custom Routines
 

Because java is an OOP language, all custom routines belong to a specific class and are therefore referred to as methods.

All methods in Java must return something so even with procedures, you return a "void".

public void sayHello(String pName) {
  System.out.println("Hello" + pName);
}
 

public int add(int p1, int p2) {
  return p1 + p2;
}
Posted By Mike Prestwood, Post #101599, KB Topic: Language Details
-Collapse +Expand 23. Java Inheritance (extends ParentClass)
 

Simple syntax example of class inheritance.

In the following example, a terminator T-600 is-an android. 

public class Android {
}
 
public class T-600 extends Android {
}
Posted By Mike Prestwood, Post #101392, KB Topic: Language Details
-Collapse +Expand 24. Java Inlining (Automatic)
 

The Java compiler automatically inlines when it determines  a benefit. The use of final methods is considered a compiler hint to tell the compiler to inline the method if beneficial.

Posted By Mike Prestwood, Post #101867, KB Topic: Language Details
-Collapse +Expand 25. Java Overloading
 

Java Overloading

  • Operator - No. Sun deliberately choose not include operator overloading in the Java language.
  • Method - Yes.
Posted By Mike Prestwood, Post #101461, KB Topic: Language Details



Topic: OOP

-Collapse +Expand 26. Java Base Class (Object)
 

The Object class is Java's single base class all classes ultimately inherit from.

public class Cyborg {
}

or you can specify the base class (or any other class):

public class Cyborg extends Object {
}
Posted By Mike Prestwood, Post #101409, KB Topic: OOP
-Collapse +Expand 27. Java Constructors (Use class name)
 

A method with the same name as the class.

public class Cyborg{
  //Constructors have the same name as the class.
  public Cyborg() {
  }
}
Posted By Mike Prestwood, Post #101420, KB Topic: OOP
-Collapse +Expand 28. Java final class (Final)
 

In Java, there is the concept of a final class.

Posted By Mike Prestwood, Post #101425, KB Topic: OOP
-Collapse +Expand 29. Java finalize (finalize())
 

Java has a garbage collection algorythm that runs as a background task so it has no destructors. You can use the finalize() method to close additonal resources such as file handles.

protected void finalize() throws Throwable {
try {
close(); // close open files
} finally {
super.finalize();
}
}
Posted By Mike Prestwood, Post #101431, KB Topic: OOP
-Collapse +Expand 30. Java Inheritance-Multiple (Interfaces Only)
 

Java does not support multiple implementation inheritance. Each class can have only one parent class (a single inheritance path). In Java, you can use multiple interface usage to design in a multiple class way horizontally in a class hierarchy.

Posted By Mike Prestwood, Post #101446, KB Topic: OOP
-Collapse +Expand 31. Java Interfaces (Yes)
 

General Info: Interface

An element of coding where you define a common set of properties and methods for use with the design of two or more classes.

Both interfaces and abstract classes are types of abstraction. With interfaces, like abstract classes, you cannot provide any implementation. However, unlike abstract classes, interfaces are not based on inheritance. You can apply an Interface to any class in your class tree. In a real sense, interfaces are a technique for designing horizontally in a class hierarchy (as opposed to inheritance where you design vertically). Using interfaces in your class design allows your system to evolve without breaking existing code.

Java Interfaces

Posted By Mike Prestwood, Post #101437, KB Topic: OOP
-Collapse +Expand 32. Java Member Field
 

In Java, you can set the scope of a field member to public, protected, or private. Additional modifiers are static, abstract, final (assign only once), strictfp (strict floating point values) transient (do not save to persistent storage), and volatile (all threads see same value).

Posted By Mike Prestwood, Post #101756, KB Topic: OOP

Follow PrestwoodBoards on: 


©1995-2019 PrestwoodBoards  [Security & Privacy]
Professional IT Services: Coding | Websites | Computer Tech