Introduction to Java programming
Introduction to Java programming
This tutorial explains the installation and usage of the Java
                        programming language. It also
                        contains examples
                        for standard
                        programming tasks.
                        
                     
Table of Contents
- 1. Introduction to Java
 - 
- 1.1. History
 - 1.2. Java Virtual machine
 - 1.3. Java Runtime Environment vs. Java Development Kit
 - 1.4. Characteristics of Java
 - 1.5. Development Process with Java
 - 1.6. Garbage collector
 - 1.7. Classpath
 
 - 2. Installation of Java
 - 3. Your first Java program
 - 
- 3.1. Write source code
 - 3.2. Compile and run your Java program
 - 3.3. Using the classpath
 
 - 4. Java basic terms
 - 
- 4.1. Basics: Package, Class and Object
 - 4.2. Package
 - 4.3. Class
 - 4.4. Object
 - 4.5. Inheritance
 - 4.6. Override methods and the @override annotation
 - 4.7. Object has superclass
 
 - 5. Variables and methods
 - 
- 5.1. Variable
 - 5.2. Instance variable
 - 5.3. Local variable
 - 5.4. Methods
 - 5.5. Main method
 - 5.6. Constructor
 
 - 6. Modifiers
 - 
- 6.1. Access modifiers
 - 6.2. Other modifiers
 
 - 7. Import statements
 - 
- 7.1. Usage of import statements
 - 7.2. Static imports
 
 - 8. More Java language constructs
 - 
- 8.1. Interface
 - 8.2. Class methods and class variables
 - 8.3. Abstract class and methods
 
 - 9. Cheat Sheets
 - 
- 9.1. Working with classes
 - 9.2. Working with local variable
 
 - 10. Integrated Development Environment
 - 11. Exercises - Creating Java objects and methods
 - 
- 11.1. Create a Person class and instantiate it
 - 11.2. Use constructor
 - 11.3. Define getter and setter methods
 - 11.4. Create an Address object
 
 - 12. Solution - Creating Java objects and methods
 - 
- 12.1. Create a Person class and instantiate it
 - 12.2. Use constructor
 - 12.3. Define getter and setter methods
 - 12.4. Solution - Create an Address object
 
 - 13. Java statements
 - 
- 13.1. if-then and if-then-else
 - 13.2. Switch
 - 13.3. Boolean Operations
 
 - 14. Loops in Java
 - 
- 14.1. The for loop
 - 14.2. The while loop
 - 14.3. The do while loop
 
 - 15. Arrays
 - 
- 15.1. Arrays in Java
 - 15.2. Enhanced for loop for Arrays and Collections
 
 - 16. Working with Strings
 - 17. Type Conversion
 - 
- 17.1. Conversion to String
 - 17.2. Conversion from String to Number
 - 17.3. Double to int
 - 17.4. SQL Date conversions
 
 - 18. Your first graphical user interface application (GUI)
 - 19. Schedule tasks
 - 20. Thank you
 
1. Introduction to Java
Java is a programming language created by James Gosling from
                  Sun Microsystems in 1991. The first publicly available version of
                  Java
                  (Java 1.0) was released in 1995.
                  
               
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform allows software developers to write program code in other languages than the Java programming language and still runs on the Java virtual machine. The Java platform is usually associated with the Java virtual machine and the Java core libraries.
Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.
From the Java programming language the Java platform evolved. The Java platform allows software developers to write program code in other languages than the Java programming language and still runs on the Java virtual machine. The Java platform is usually associated with the Java virtual machine and the Java core libraries.
The Java
                  virtual
                  machine (JVM) is a software implementation of a
                  computer that
                  executes programs like a real machine.
                  
               
The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
The Java virtual machine is written specifically for a specific operating system, e.g. for Linux a special implementation is required as well as for Windows.
Java programs are compiled by the Java compiler into bytecode. The Java virtual machine interprets this bytecode and executes the Java program.
A Java distribution comes typically in two flavors, the
                  Java Runtime Environment
                  (JRE)
                  and the
                  Java Development Kit
                  (JDK).
                  
               
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries and contains the necessary functionality to start Java programs.
The JDK contains in addition the development tools necessary to create Java programs. The JDK consists therefore of a Java compiler, the Java virtual machine, and the Java class libraries.
The target of Java is to write a program once and then run
                  this
                  program on multiple operating systems.
                  
               
Java has the following properties:
The Java syntax is similar to C++. Java is case sensitive, e.g. variables called
Java has the following properties:
- 
                        Platform independent: Java programs use the Java virtual
                           machine
                           as
                           abstraction and do not access the operating system
                           directly. This makes Java programs highly portable. A Java
                           program
                           (which is standard complaint and follows certain rules) can
                           run
                           unmodified on all supported platforms, e.g. Windows or Linux.
                           
                        
 - 
                        Object-orientated programming language:
                           Except the primitive
                           data types, all elements in Java are objects.
                           
                        
 - 
                        Strongly-typed programming language: Java is
                           strongly-typed,
                           e.g. the types of the used variables must be pre-defined and
                           conversion to
                           other objects is relatively strict, e.g. must be done
                           in most cases by the programmer.
                           
                        
 - 
                        Interpreted and compiled language: Java source
                           code is
                           transferred into the bytecode format which does not depend on the
                           target
                           platform. These bytecode instructions will be interpreted by
                           the Java
                           Virtual
                           machine (JVM). The JVM contains a so called
                           Hotspot-Compiler which
                           translates performance critical bytecode
                           instructions
                           into native
                           code instructions.
                           
                        
 - 
                        Automatic memory management: Java manages the memory
                           allocation and de-allocation for creating new objects. The
                           program
                           does not have direct access to the memory. The so-called garbage
                           collector deletes automatically objects to which no active pointer
                           exists.
                           
                        
 
The Java syntax is similar to C++. Java is case sensitive, e.g. variables called
myValue
                  and
                  myvalue
                  are treated as different
                  variables.
                  
               
Java source files are written as plain text documents.
                  The programmer
                  typically writes Java source code in an
                  Integrated Development Environment
                  (IDE) for
                  programming. An IDE supports the programmer in the task of
                  writing code, e.g.
                  it provides auto-formating of the source code,
                  highlighting of the
                  important keywords, etc.
                  
               
At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. These instructions are stored in
At some point the programmer (or the IDE) calls the Java compiler (javac). The Java compiler creates the bytecode instructions. These instructions are stored in
.class
                  files and can be executed by the Java Virtual Machine.
                  
               
The JVM automatically re-collects the memory which is not
                  referred to
                  by other objects.
                  The java
                  garbage collector
                  checks all object references and find the objects which can be
                  automatically released.
                  
               
While the garbage collector releases the programmer from the need to explicitly manage memory the programmer still need to ensure that he does not keep unneeded object references otherwise the garbage collector cannot release the associated memory. Keeping unneeded object references are typically called memory leaks.
While the garbage collector releases the programmer from the need to explicitly manage memory the programmer still need to ensure that he does not keep unneeded object references otherwise the garbage collector cannot release the associated memory. Keeping unneeded object references are typically called memory leaks.
The
                  classpath
                  defines where the Java compiler and Java runtime look
                  for
                  
For example if you want to use an external Java library you have to add this library to your classpath to use it in your program.
.class
                  files to
                  load. This instructions can be used in the Java program.
                  
               For example if you want to use an external Java library you have to add this library to your classpath to use it in your program.
Java might already be
               installed on your machine. You can test
               this by
               opening a console
               (if you are using Windows: Win+R, enter
               cmd
               and press Enter) and by typing in the
               following command:
               
            
If Java is correctly installed, you should see some information about your Java installation. If the command line returns the information that the program could not be found, you have to install Java. The central website for installing Java is the following URL:
If you have problems installing Java on your system, search via Google for How to install JDK on
java -version
If Java is correctly installed, you should see some information about your Java installation. If the command line returns the information that the program could not be found, you have to install Java. The central website for installing Java is the following URL:
http://java.com
If you have problems installing Java on your system, search via Google for How to install JDK on
YOUR_OS
                  . This
               should result
               in
               helpful links. Replace
               YOUR_OS
               with your
               operating
               system, e.g.
               Windows,
               Ubuntu, Mac OS X, etc.
               
            
The following Java program is developed under Linux using a text
                  editor and the command line.
                  The
                  process on other operating system
                  should be similar and but
                  is not
                  covered
                  in this description.
                  
               
Select or create a new directory which will be used for your Java development. In this description the path
Open a text editor which supports plain text, e.g. gedit under Linux or Notepad under Windows and write the following source code.
Save the source code in your javadir directory with the
Select or create a new directory which will be used for your Java development. In this description the path
\home\vogella\javastarter
                  is used. On Microsoft Windows
                  your might want to use
                  c:\temp\javastarter. This path is
                  called
                  javadir
                  in the following description.
                  
               Open a text editor which supports plain text, e.g. gedit under Linux or Notepad under Windows and write the following source code.
// A small Java program public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } }
Warning
Do not use a rich editor like Microsoft Word or LibreOffice for writing Java code. If in doubt, google for "Plain text editor for [your_OS]".Save the source code in your javadir directory with the
HelloWorld.java
                  filename. The name of a Java source
                  file must always equals
                  the class
                  name (within the source code)
                  and end
                  with the
                  .java
                  extension. In this example
                  the
                  filename must be
                  HelloWorld.java
                  because
                  the
                  class is called
                  HelloWorld.
                  
               
Open a shell for command line access.
                  
               
Switch to the
                  javadir
                  directory with the command cd javadir,
                  for
                  example in the above example
                  via the
                  
Compile your Java source file into a class file with the following command.
Afterwards list again the content of the directory with the
You can now start your compiled Java program. Ensure that you are
                  still in the
                  
The system should write "Hello World" on the command line.
Tip
If you don't know how to do this, google for "How to open a shell under [your_OS]".cd \home\vogella\javastarter
                     
                  command.
                  Use the
                  ls
                  command (dir
                  under Microsoft Windows) to verify
                  that
                  the source file is in the
                  directory.Compile your Java source file into a class file with the following command.
javac HelloWorld.java
Afterwards list again the content of the directory with the
ls
                  or
                  dir
                  command. The
                  directory contains now a file "HelloWorld.class". If you
                  see
                  this
                  file you have successfully compiled your first Java source
                  code
                  into
                  bytecode.
                  
               Tip:
By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with the -d compiler flag.jardir
                  directory and enter the following command to start your Java program.java HelloWorld
The system should write "Hello World" on the command line.
You can use the classpath to run the program from another place
                  in your directory.
                  
               
Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any directory you want. Type:
If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass
To use the class type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.
Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to any directory you want. Type:
java HelloWorld
If you are not in the directory in which the compiled class is stored then the system should result an error message Exception in thread "main" java.lang.NoClassDefFoundError: test/TestClass
To use the class type the following command. Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.
java -classpath "mydirectory" HelloWorld 
It is important to understand the base terminology of Java in
                  terms of
                  packages,
                  classes
                  and
                  objects. This section gives an overview of these terms.
                  
               
Java groups classes into functional
                  packages.
                  
               
Packages are typically used to group classes into logical units. For example all graphical views of an application might be placed in the same package called
It is common practice to use the reverse domain name of the company as top level package. For example the company might own the domain, vogella.com and in this example the Java packages of this company starts with
Other main reason for the usage of packages is to avoid name collisions of classes. A name collision occurs if two programmers give the same fully qualified name to a class. The fully qualified name of a class in Java consists out of the package name followed by a dot (.) and the class name.
Without packages, a programmer may create a Java class called
Packages are typically used to group classes into logical units. For example all graphical views of an application might be placed in the same package called
com.vogella.webapplication.views.
                  
               It is common practice to use the reverse domain name of the company as top level package. For example the company might own the domain, vogella.com and in this example the Java packages of this company starts with
com.vogella.
                  
               Other main reason for the usage of packages is to avoid name collisions of classes. A name collision occurs if two programmers give the same fully qualified name to a class. The fully qualified name of a class in Java consists out of the package name followed by a dot (.) and the class name.
Without packages, a programmer may create a Java class called
Test. Another programmer may create
                  a class with the same name. With
                  the
                  usage of packages you can
                  tell the system which class to call.
                  For
                  example if the first programmer puts
                  the
                  Test
                  class into package
                  report
                  and the second programmer
                  puts his class into package
                  xmlreader
                  you can distinguish between these classes by using the
                  fully qualified name, e.g.
                  xmlreader.Test
                  or
                  report.Test.
                  
               
 Def.: Template that describes the data and behavior
                        associated with an instance of that class.
                        
                  
               
In Java source code a class is
                  defined by the
                  class
                  keyword and must start with a capital letter. The body of a class is
                  surrounded by {}.
                  
               
The data associated with a class is stored in variables ; the behavior associated to a class or object is implemented with methods.
A class is contained in a Java source file with the same name as the class plus the .java extension.
Note
The class can be seen as the blueprint of an object. It describes how an object is created.package test; class MyClass { }
The data associated with a class is stored in variables ; the behavior associated to a class or object is implemented with methods.
A class is contained in a Java source file with the same name as the class plus the .java extension.
 Def.: An object is an instance of a class.
                  
               
The object is the real element which has data and can perform actions. Each object is created based on the class definition.
The object is the real element which has data and can perform actions. Each object is created based on the class definition.
A class can be derived from another class. In this case this
                  class is
                  called a
                  subclass. Another common phrase is that
                  a class extends another class.
                  
               
The class from which the subclass is derived is called a superclass.
Inheritance allows a class to inherit the behavior and data definitions of another class.
The following codes demonstrates how a class can extend another class. In Java a class can only extend a maximum of one class.
The class from which the subclass is derived is called a superclass.
Inheritance allows a class to inherit the behavior and data definitions of another class.
The following codes demonstrates how a class can extend another class. In Java a class can only extend a maximum of one class.
package com.jix.javaintro.base; class MyBaseClass { void hello(){ System.out.println("Hello from MyBaseClass"); } }
package com.vogella.javaintro.base; class MyExtensionClass extends MyBaseClass { }
If a class extends another class it inherits the methods from
                  its
                  superclass. If it wants to change these methods it can
                  override
                  these methods. To override a method you use the same method signature
                  in the source code of the subclass.
                  
               
To indicate to the reader of the source code and the Java compiler that you have the intention to override a method you can use the
The following code demonstrates how you can override a method from a superclass.
To indicate to the reader of the source code and the Java compiler that you have the intention to override a method you can use the
@override annotation.
                  
               The following code demonstrates how you can override a method from a superclass.
package com.vogella.javaintro.base; class MyBaseClass { void hello(){ System.out.println("Hello from MyBaseClass"); } }
package com.vogella.javaintro.base; class MyExtensionClass2 extends MyBaseClass { }
Tip:
It is good practice to always use the@override
                     annotation. This way the Java compiler validates if you did override
                     all methods as intended and prevents errors.
                     
                  
Every object in Java implicitly extends the
                  
Object
                  class. The class defines the following methods for every Java
                  object:
                  
               - 
                        
equals(o1)allows to check if the current object is equal to o1
 - 
                        
getClass()returns the class of the object
 - 
                        
hashCode()returns an identifier of the current object
 - 
                        
toString()Give a string representation of the current object
 
Variables
                  allow the Java program to store values during the
                  runtime of the
                  program.
                  
               
A variable can either be a primitive variable or a reference variable. A primitive variable contains value while the reference variable contains a reference (pointer) to the object. Hence if you compare two reference variables, you compare if both point to the same object. To compare objects use the
A variable can either be a primitive variable or a reference variable. A primitive variable contains value while the reference variable contains a reference (pointer) to the object. Hence if you compare two reference variables, you compare if both point to the same object. To compare objects use the
object1.equals(object2)
                  method call.
                  
               
Instance variable is associated with an instance of
                  the class
                  (also called object). Access works over these objects.
                  
               
Instance variables can have any access control and can be marked final or transient. Instance variables marked as final can not be changed after assigned to a value.
Instance variables can have any access control and can be marked final or transient. Instance variables marked as final can not be changed after assigned to a value.
Local (stack) variable declarations cannot have access
                  modifiers.
                  
               
final is the only modifier available to local variables. This modifier defines that the variable can not be changed after first assignment.
Local variables do not get default values, so they must be initialized before use.
final is the only modifier available to local variables. This modifier defines that the variable can not be changed after first assignment.
Local variables do not get default values, so they must be initialized before use.
A method is a block of code with parameters and a return value.
                  It can be called on the object.
                  
               
Method can be declared with var-args. In this case the method declares a parameter which accepts from zero to many arguments (syntax: type .. name;) A method can only have one var-args parameter and this must be the last parameter in the method.
Overwrite of a superclass method: A method must be of the exact same return parameter and the same arguments. Also the return parameter must be the same. Overload methods: An overloaded method is a method with the same name, but different arguments. The return type can not be used to overload a method.
package com.jix.javaintro.base; public class MyMethodExample { void tester(String s) { System.out.println("Hello World"); } }
Method can be declared with var-args. In this case the method declares a parameter which accepts from zero to many arguments (syntax: type .. name;) A method can only have one var-args parameter and this must be the last parameter in the method.
Overwrite of a superclass method: A method must be of the exact same return parameter and the same arguments. Also the return parameter must be the same. Overload methods: An overloaded method is a method with the same name, but different arguments. The return type can not be used to overload a method.
A public static method with the following signature can be used
                  to
                  start a Java application. Such a method is typically called
                  
main
                  method.
                  
               public static void main(String[] args){ }
A class contains
                  constructors
                  that are invoked to create objects
                  based on the class definition.
                  
               
Constructor declarations look like method declarations except that they use the name of the class and have no return type.
A class can have several constructors with different parameters. Each class must define at least one constructor.
In the following example the constructor of the class expects a parameter.
If no explicit constructor is defined the compiler adds implicitly a constructor. If the class is sub-classed then the constructor of the super class is always implicitly called in this case.
In the following example the definition of the constructor without parameters (also known as the empty constructor) is unnecessary. If not specified the compiler would create one.
The naming conversion for creating a constructor is the following:
Every object is created based on a constructor. This constructor method is the first statement called before anything else can be done with the object.
Constructor declarations look like method declarations except that they use the name of the class and have no return type.
A class can have several constructors with different parameters. Each class must define at least one constructor.
In the following example the constructor of the class expects a parameter.
package com.vogella.javaintro.base; public class MyConstructorExample2 { String s; public MyConstructorExample2(String s) { this.s = s; } }
If no explicit constructor is defined the compiler adds implicitly a constructor. If the class is sub-classed then the constructor of the super class is always implicitly called in this case.
In the following example the definition of the constructor without parameters (also known as the empty constructor) is unnecessary. If not specified the compiler would create one.
package com.vogella.javaintro.base; public class MyConstructorExample { // Unnecessary, would be created by the compiler if left out public MyConstructorExample() { } }
The naming conversion for creating a constructor is the following:
classname
                     (Parameter p1, ..) {}
                     .
                  
               Every object is created based on a constructor. This constructor method is the first statement called before anything else can be done with the object.
There are three access modifiers keywords available in Java.
                  public,
                  protected
                  and
                  private.
                  
               
There are four access levels: public, protected, default and private. They define how the corresponding element is visible to other components.
If something is declared public, e.g. classes or methods can be freely created or called by other Java objects. If something is declared private, e.g. a method, it can only be accessed within the class in which it is declared.
protected and default are similar. A protected class can be accessed from the package and sub-classes outside the package while a default class can get only accessed via the same package.
The following table describes the visibility:
                        
There are four access levels: public, protected, default and private. They define how the corresponding element is visible to other components.
If something is declared public, e.g. classes or methods can be freely created or called by other Java objects. If something is declared private, e.g. a method, it can only be accessed within the class in which it is declared.
protected and default are similar. A protected class can be accessed from the package and sub-classes outside the package while a default class can get only accessed via the same package.
The following table describes the visibility:
Table 1. Access Level
| Modifier | Class | Package | Subclass | World | 
|---|---|---|---|---|
| public | Y | Y | Y | Y | 
| protected | Y | Y | Y | N | 
| no modifier | Y | Y | N | N | 
| private | Y | N | N | N | 
In Java you have to access a class always via its
                  full-qualified name, e.g. the package name and the class name.
                  
               
You can add
You can add
import
                  statements for classes or packages into your class file, which allow
                  you to use the related classes in your code without the package
                  qualifier.
                  
               
Static import is a feature that allows members (fields and
                  methods)
                  which are defined in a class
                  with the
                  
The feature provides a typesafe mechanism to include constants into code without having to reference the class that originally defined the field.
public static
                  access modifier
                  to be used in Java code
                  without specifying the class
                  in
                  which the member
                  is defined.
                  
               The feature provides a typesafe mechanism to include constants into code without having to reference the class that originally defined the field.
Interfaces
                  are contracts for what a class can do but they say
                  nothing about the
                  way in which the class must do it.
                  
               
An interface is a type similar to a class. Like a class an interface defines methods.
An interface can have only abstract methods, no concrete methods are allowed. Methods defined in interfaces are by default public and abstract – explicit declaration of these modifiers is optional.
Interfaces can have constants which are always implicitly public, static and final.
A class can implement an interface. In this case it must provide concrete implementations of the interface methods.
If you override a method defined by an interface you can also use the
The following code shows an example implementation of an interface and its usage within a class.
An interface is a type similar to a class. Like a class an interface defines methods.
An interface can have only abstract methods, no concrete methods are allowed. Methods defined in interfaces are by default public and abstract – explicit declaration of these modifiers is optional.
Interfaces can have constants which are always implicitly public, static and final.
A class can implement an interface. In this case it must provide concrete implementations of the interface methods.
If you override a method defined by an interface you can also use the
@override
                  annotation.
                  
               The following code shows an example implementation of an interface and its usage within a class.
package com.vogella.javaintro.base; public interface MyDefinition { // constant definition String URL="http://www.vogella.com"; // define several method stubs void test(); void write(String s); }
package com.vogella.javaintro.base; public class MyClassImplementation implements MyDefinition { @Override public void test() { // TODO Auto-generated method stub } @Override public void write(String s) { // TODO Auto-generated method stub } }
Class methods and class variables are associated with the class
                  and not
                  an instance of the class, i.e. objects. To refer to these
                  element you can use the
                  classname and a dot (".") followed by the
                  class
                  method or class
                  variable name.
                  
               
Class methods and class variables are declared with the
An example for the usage of a static field is
If you define a static variable the Java runtime environment associates one class variable for a class no matter how many instances (objects) exists. The static variable can therefore be seen as a global variable.
The following code demonstrates the usage of
If a variable should be defined as constant, you declare it with the
The static method runs without any instance of the class, it cannot directly access non-static variables or methods.
Class methods and class variables are declared with the
static
                  keyword. Class methods are also called
                  static methods
                  and class variables are also called
                  static variables
                  or
                  static fields.
                  
               An example for the usage of a static field is
println
                  of the following statement:
                  System.out.println("Hello World").
                  out
                  is a static field, an object of type
                  PrintStream, and you call the
                  println()
                  method on this object.
                  
               If you define a static variable the Java runtime environment associates one class variable for a class no matter how many instances (objects) exists. The static variable can therefore be seen as a global variable.
The following code demonstrates the usage of
static
                  fields.
                  
               package com.vogella.javaintro.base; public class MyStaticExample { static String PLACEHOLDER = "TEST"; static void test() { System.out.println("Hello"); } }
package com.vogella.javaintro.base; public class Tester { public static void main(String[] args) { System.out.println(MyStaticExample.PLACEHOLDER); MyStaticExample.test(); } }
If a variable should be defined as constant, you declare it with the
static
                  and the
                  final
                  keyword.
                  
               The static method runs without any instance of the class, it cannot directly access non-static variables or methods.
A class and method can be declared as
                  
If a class has at least one method which only contain the declaration of the method but not the implementation then this class is
If a class contains an abstract method it also needs to get defined with the keyword
The following example shows an abstract class.
abstract. An
                  abstract
                  class can not be directly instantiated.
                  
               If a class has at least one method which only contain the declaration of the method but not the implementation then this class is
abstract
                  and
                  can not be instantiated. Sub-classes need then to define the
                  methods
                  except if they are also declared as abstract.
                  
               If a class contains an abstract method it also needs to get defined with the keyword
abstract.
                  
               The following example shows an abstract class.
package com.vogella.javaintro.base; public abstract class MyAbstractClass { abstract double returnDouble(); }
The following can be used as a reference for certain task which
               you have to do.
               
            
While programming Java you have to create several classes,
                  methods, instance variables. The following uses the package test.
                  
               
                        
Table 2. 
| What to do | How to do it | 
|---|---|
| Create a new class called MyNewClass. | package test; public class MyNewClass { }  | 
                           
Create a new attribute (instance variable) called
                                 var1
                                 of type String
                                 in the
                                 MyNewClass
                                 class
                                 
                               | 
                              package test; public class MyNewClass { private String var1; }  | 
                           
Create a Constructor for your
                                 MyNewClass
                                 class which has a
                                 String
                                 parameter and assigns the value of it to
                                 the
                                 var1
                                 instance
                                 variable.
                                 
                               | 
                              package test; public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } }  | 
                           
| Create a new method called doSomeThing in your class which does not return a value and has no parameters | package test; public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } public void doSomeThing() { } }  | 
                           
| Create a new method called doSomeThing2 in your class which does not return a value and has two parameters, a int and a Person | package test; public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } public void doSomeThing() { } public void doSomeThing2(int a, Person person) { } }  | 
                           
| Create a new method called doSomeThing2 in your class which returns an int value and has three parameters, two Strings and a Person | package test; public class MyNewClass { private String var1; public MyNewClass(String para1) { var1 = para1; // or this.var1= para1; } public void doSomeThing() { } public void doSomeThing2(int a, Person person) { } public int doSomeThing3(String a, String b, Person person) { return 5; // Any value will do for this example } }  | 
                           
| Create a class called MyOtherClass with two instance variables. One will store a String, the other will store a Dog. Create getter and setter for these variables. | package test; public class MyOtherClass { String myvalue; Dog dog; public String getMyvalue() { return myvalue; } public void setMyvalue(String myvalue) { this.myvalue = myvalue; } public Dog getDog() { return dog; } public void setDog(Dog dog) { this.dog = dog; } }  | 
                           
A local variable must always be declared in a method. 
                        
Table 3. 
| What to do | How to do it | 
|---|---|
| Declare a (local) variable of type string. | String variable1; | 
| Declare a (local) variable of type string and assign "Test" to it. | String variable2 = "Test"; | 
| Declare a (local) variable of type Person | Person person; | 
| Declare a (local) variable of type Person, create a new Object and assign the variable to this object. | Person person = new Person(); | 
| Declare a array of type String | String array[]; | 
| Declare a array of type Person and create an array for this variable which can hold 5 Persons. | Person array[]= new Person[5]; | 
| Assign 5 to the int variable var1 (which was already declared); | var1 = 5; | 
| Assign the existing variable pers2 to the exiting variable pers1; | pers1 = pers2; | 
| Declare a ArrayList variable which can hold objects of type Person | ArrayList<Person> persons; | 
| Create a new ArrayList with objects of type Person and assign it to the existing variable persons | persons = new ArrayList<Person>(); | 
| Declare a ArrayList variable which can hold objects of type Person and create a new Object for it. | ArrayList<Person> persons = new ArrayList<Person>(); | 
The previous chapter explained how to create and compile a Java
               program on the command line. A Java Integrated Development Environment
               (IDE) provides lots of ease of use functionality for creating java
               programs. There are other very powerful IDE's available, for example
               the
               Eclipse IDE.
               .
               
            
For an introduction on how to use the Eclipse IDE please see Eclipse IDE Tutorial.
The remaining description uses the phrase: Create a Java project called... ". This refers to creating a Java project in Eclipse. If you are using a different IDE please follow the required steps in this IDE.
For an introduction on how to use the Eclipse IDE please see Eclipse IDE Tutorial.
The remaining description uses the phrase: Create a Java project called... ". This refers to creating a Java project in Eclipse. If you are using a different IDE please follow the required steps in this IDE.
Create a new Java project called
                  
Create a class called Person.
Add three instance variables to it, one for storing the first name of the person, on for storing the last name and one for storing the age of the Person.
Use the constructor of the Person object to set the values to some default value.
Write a public method called writeName() which uses the
Create a new class called Main with a
com.vogella.javastarter.exercises1
                  and a package with the same name.
                  
               Create a class called Person.
Add three instance variables to it, one for storing the first name of the person, on for storing the last name and one for storing the age of the Person.
Use the constructor of the Person object to set the values to some default value.
Write a public method called writeName() which uses the
System.out.println(
                  method to print the first name of the person to the console.
                  
               Create a new class called Main with a
public static void main(String[] args). In this method create an instance of the
                  Person
                  class.
                  
               
Add a constructor to your
                  
Create in your main method two objects of type
Person
                  class which takes the first name, last name and the age as parameter.
                  Assign the values to your instance variables.
                  
               Create in your main method two objects of type
Person
                  and call the
                  writeName
                  method on it.
                  
               
Define methods which allow you to read the values of the
                  instance
                  variables and to set them. These methods are called
                  setter
                  and
                  getter.
                  
               
Getters should start with
Setter should start with
` For example the variable called firstName would have the
Change your
Getters should start with
get
                  followed by the variable name whereby the first letter of the
                  variable is capitized.
                  
               Setter should start with
set
                  followed by the variable name whereby the first letter of the
                  variable is capitized.
                  
               ` For example the variable called firstName would have the
getFirstName()
                  getter method and the
                  setFirstName(String s)
                  setter method.
                  
               Change your
main
                  method so that you create one person object and use the setter
                  method to change the last name.
                  
               
The following is a potential solution for
                  Section 11.1, “Create a Person class and instantiate it”.
                  
               
package exercises.exercise04; class Person { String firstname = "Jim"; String lastname = "Knopf"; int age = 12; void writeName() { // Writes the firstname System.out.println(firstname); // Alternatively you can combine strings with + System.out.println(firstname + " " + lastname + "" + age); } }
package exercises.exercise04; public class Main { public static void main(String[] args) { Person person = new Person(); person.writeName(); } }
package com.vogella.javastarter.exercises1; class Person { String firstName; String lastName; int age; public Person(String a, String b, int value) { firstName = a; lastName = b; age=value; } void writeName() { // Writes the firstname System.out.println(firstName); // Alternatively you can combine strings with + System.out.println(firstName + " " + lastName + "" + age); } }
package com.vogella.javastarter.exercises1; public class Main { public static void main(String[] args) { Person person = new Person("Jim", "Knopf" , 12); person.writeName(); // Reuse the same variable and assign new object to it person = new Person("Henry", "Ford", 104); person.writeName(); } }
package com.vogella.javastarter.exercises1; class Person { String firstName; String lastName; int age; public Person(String a, String b, int value) { firstName = a; lastName = b; age = value; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } void writeName() { // Writes the firstname System.out.println(firstName); // Alternatively you can combine strings with + System.out.println(firstName + " " + lastName + "" + age); } }
package com.vogella.javastarter.exercises1; public class Main { public static void main(String[] args) { Person person = new Person("Jim", "Knopf", 21); Person person2 = new Person("Jill", "Sanders", 20); // Jill get married to Jim // and takes his name person2.setLastName("Knopf"); person2.writeName(); } }
package com.vogella.javastarter.exercises1; public class Address { private String street; private String number; private String postalCode; private String city; private String country; public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getPostalCode() { return postalCode; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String toString() { return street + " " + number + " " + postalCode + " " + city + " " + country; } }
package com.vogella.javastarter.exercises1; class Person { String firstName; String lastName; int age; private Address address; public Person(String a, String b, int value) { firstName = a; lastName = b; age=value; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } void writeName() { // Writes the firstname System.out.println(firstName); // Alternatively you can combine strings with + System.out.println(firstName + " " + lastName + "" + age); } }
package com.vogella.javastarter.exercises1; public class Main { public static void main(String[] args) { // I create a person Person pers = new Person("Jim", "Knopf", 31); // I set the age of the person to 32 pers.setAge(32); // Just for testing I write this to the console System.out.println(pers.toString()); /* * Actually System.out.println calls always toString, if you do not * specify it so you could also have written System.out.println(pers); */ // I create an address Address address = new Address(); // I set the values for the address address.setCity("Heidelberg"); address.setCountry("Germany"); address.setNumber("104"); address.setPostalCode("69214"); address.setStreet("Musterstr."); // I assign the address to the person pers.setAddress(address); // I do not need address any more address = null; // person is moving to the next house in the same street pers.getAddress().setNumber("105"); } }
The Java language defines certain statements with a predefined
               meaning.
               The following description lists some of them.
               
            
The
                  
The following example code shows a class with two methods. The first method demonstrates the usage of
if-then
                  statement is a control flow statement. A block of code is only
                  executed if the test specified by the if part evaluates to
                  true. The optional
                  else
                  block is executed if the
                  if
                  part evaluates to
                  false.
                  
               The following example code shows a class with two methods. The first method demonstrates the usage of
if-then
                  and the second method demonstrates the usage of
                  if-then-else.
                  
               
The switch statement can be used to handle several
                  alternatives
                  if they are based on the same constant value.
                  
                  
               
switch (expression) { case constant1: command; break; // Will prevent that the other cases or also executed case constant2: command; break; ... default: } Example: switch (cat.getLevel()) { case 0: return true; case 1: if (cat.getLevel() == 1) { if (cat.getName().equalsIgnoreCase(req.getCategory())) { return true; } } case 2: if (cat.getName().equalsIgnoreCase(req.getSubCategory())) { return true; } }
Use == to compare two primitives or to see if two references
                  refers to the same object. Use the equals() method to see if
                  two
                  different objects are equal.
                  
               
&& and || are both Short Circuit Methods which means that they terminate once the result of an evaluation is already clear. Example (true || ....) is always true while (false && ...) always false is. Usage:
(var !=null && var.method1()..) ensures that var is not null before doing the real check.
                        
&& and || are both Short Circuit Methods which means that they terminate once the result of an evaluation is already clear. Example (true || ....) is always true while (false && ...) always false is. Usage:
(var !=null && var.method1()..) ensures that var is not null before doing the real check.
Table 4. Boolean
| Operations | Description | 
|---|---|
| == | Is equal, in case of objects the system checks if the reference variable point to the same object, is will not compare the content of the objects! | 
| && | And | 
| != | is not equal, similar to the "==" | 
| a.equals(b) | Checks if string a equals b | 
| a.equalsIgnoreCase(b) | Checks if string a equals b while ignoring lower cases | 
| If (value ? false : true) {} | Return true if value is not true. Negotiation | 
A for loop is a repetition control structure that allows you to
                  write a block of code which is execute a specific number of
                  times. The
                  syntax is the following.
                  
               
The following shows an example for a for loop.
for(initialization; expression; update_statement)
{
   //block of code to run 
} 
The following shows an example for a for loop.
public class ForTest { public static void main(String args[]) { for(int i = 1; i < 10; i = i+1) { System.out.println("value of i : " + i); } } }
Tip
For Arrays and Collections where is also an enhanced for loop available. This loop is covered in the Array description.
A while loop is a repetition control structure that allows you
                  to
                  write a block of code which is execute until a specific condition
                  evaluates to false. The
                  syntax is the following.
                  
               
The following shows an example for a while loop.
while(expression)
{
   //block of code to run 
} 
The following shows an example for a while loop.
public class WhileTest { public static void main(String args[]) { int x = 1; while (x < 10) { System.out.println("value of x : " + x); x++; } } }
The do-while loop is similar to the while loop, only that the
                  condition is checked after the execution. The
                  syntax is the following.
                  
               
The following shows an example for a do-while loop.
do { //block of code to run } while(expression);
The following shows an example for a do-while loop.
public class DoTest { public static void main(String args[]) { int x = 1; do { System.out.println("value of x : " + x); x++; } while (x < 10); } }
An array is a container object that holds a fixed number of
                  values of a single type. An item in an array is called an element.
                  Every element can be accessed via an index. The first element in an
                  array is addressed via the 0 index, the second via 1, etc.
                  
               
package com.vogella.javaintro.array; public class TestMain { public static void main(String[] args) { // declares an array of integers int[] array; // allocates memory for 10 integers array = new int[10]; // initialize values array[0] = 10; // initialize second element array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50; array[5] = 60; array[6] = 70; array[7] = 80; array[8] = 90; array[9] = 100; } }
Arrays and Collections can be processed with a simpler for loop.
                  
               
The following code demonstrates its usage.
for(declaration : expression)
{
   // body of code to be executed
} 
The following code demonstrates its usage.
package com.vogella.javaintro.array; public class TestMain { public static void main(String[] args) { // declares an array of integers int[] array; // allocates memory for 10 integers array = new int[10]; // initialize values array[0] = 10; // initialize second element array[1] = 20; array[2] = 30; array[3] = 40; array[4] = 50; array[5] = 60; array[6] = 70; array[7] = 80; array[8] = 90; array[9] = 100; for (int i : array) { System.out.println("Element at index " + i + " :" + array[i]); } } }
The following lists the most common string operations.
                     
Table 5. 
| Command | Description | 
|---|---|
| text1.equals("Testing"); | return true if text1 is equal to "Testing". The test is case sensitive. | 
| text1.equalsIgnoreCase("Testing"); | return true if text1 is equal to "Testing". The test is not case sensitive. For example it would also be true for "testing" | 
| StringBuffer str1 = new StringBuffer(); | Define a new String with a variable length. | 
| str.charat(1); | Return the character at position 1. (Strings starting with 0) | 
| str.substring(1); | Removes the first characters. | 
| str.substring(1, 5); | Gets the substring from the second to the fifths character. | 
| str.indexOf(String) | Find / Search for String Returns the index of the first occurrence of the specified string. | 
| str.lastIndexOf(String) | Returns the index of the last occurrence of the specified string. StringBuffer does not support this method. Hence first convert the StringBuffer to String via method toString. | 
| str.endsWith(String) | Returns true if str ends with String | 
| str.startsWith(String) | Returns true if str starts with String | 
| str.trim() | Removes leading and trailing spaces | 
| str.replace(str1,str2) | Replaces all occurrences of str1 by str2 | 
| str.concat(str1); | Concatenates str1 at the end of str. | 
| str.toLowerCase() str.toUpperCase() | Converts string to lower- or uppercase | 
| str1 + str2 | Concatenate str1 and str2 | 
| String[] zeug = myString.split("-"); String[] zeug = myString.split("\\."); | Spits myString at / into Strings. Attention: the split string is a regular expression, so if you using special characters which have a meaning in regular expressions you need to quote them. In the second example the . is used and must be quoted by two backslashes. | 
If you use variables of different types Java requires for certain
               types an explicit conversion. The following gives examples for this conversion.
            
The conversion from string to number is independent from the Locale settings, e.g. it is always using the English notification for number. In this notification a correct number format is "8.20". The German number "8,20" would result in an error.
To convert from a German number you have to use the NumberFormat class. The challenges is that if the value is for example 98.00 then the NumberFormat class would create a Long which cannot be casted to Double. Hence the following complex conversion class.
Use the following to convert from other types to Strings
                  
               
// Convert from int to String String s1 = String.valueOf (10); // "10" String s2 = // Convert from double to String String.valueOf (Math.PI); // "3.141592653589793" // Convert from boolean to String String s3 = String.valueOf (1 < 2); // "true" // Convert from date to String String s4 = String.valueOf (new Date()); // "Tue Jun 03 14:40:38 CEST 2003"
// Conversion from String to int int i = Integer.parseInt(String); // Conversion from float to int float f = Float.parseFloat(String); // Conversion from double to int double d = Double.parseDouble(String);
The conversion from string to number is independent from the Locale settings, e.g. it is always using the English notification for number. In this notification a correct number format is "8.20". The German number "8,20" would result in an error.
To convert from a German number you have to use the NumberFormat class. The challenges is that if the value is for example 98.00 then the NumberFormat class would create a Long which cannot be casted to Double. Hence the following complex conversion class.
private Double convertStringToDouble(String s) { Locale l = new Locale("de", "DE"); Locale.setDefault(l); NumberFormat nf = NumberFormat.getInstance(); Double result = 0.0; try { if (Class.forName("java.lang.Long").isInstance(nf.parse(s))) { result = Double.parseDouble(String.valueOf(nf.parse(s))); } else { result = (Double) nf.parse(new String(s)); } } catch (ClassNotFoundException e1) { e1.printStackTrace(); } catch (ParseException e1) { e1.printStackTrace(); } return result; }
Use the following to convert a Date to a SQL date
package test; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; public class ConvertDateToSQLDate { private void convertDateToSQL(){ SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date enddate = new java.util.Date("10/31/99"); java.sql.Date sqlDate = java.sql.Date.valueOf(template.format(enddate)); } public static void main(String[] args) { ConvertDateToSQLDate date = new ConvertDateToSQLDate(); date.convertDateToSQL(); } }
Use the
               Eclipse IDE to
               create a new Java project called
               com.vogella.javaintroduction.swing.
               
            
Create the following class
Create also the
You should see the following. A mesage dialog should be seen if you press the button.
Create the following class
MyFirstUI
               in
               com.vogella.javaintroduction.swing
               package.
               
            package com.vogella.javaintroduction.swing; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class MyFirstUI extends JFrame { private JCheckBox checkbox; private JTextField firstName; private JTextField lastName; public MyFirstUI() { setTitle("My First UI"); // We create a panel which will hold the UI components JPanel pane = new JPanel(new BorderLayout()); // We always have two UI elements (columns) and we have three rows int numberOfRows = 3; int numberOfColumns = 2; pane.setLayout(new GridLayout(numberOfRows, numberOfColumns)); // create and attach buttons // create a label and add it to the main window JLabel firstNamelabel = new JLabel(" Firstname: "); pane.add(firstNamelabel); firstName = new JTextField(); pane.add(firstName); JLabel lastNamelabel = new JLabel(" Lastname: "); pane.add(lastNamelabel); lastName = new JTextField(); pane.add(lastName); JButton sayHello = new JButton("Say something"); pane.add(sayHello); checkbox = new JCheckBox("Nice"); pane.add(checkbox); // add the pane to the main window getContentPane().add(pane); // Pack will make the size of window fitting to the compoents // You could also use for example setSize(300, 400); pack(); // Set a tooltip for the button sayHello .setToolTipText("This button will say something really nice of something bad"); // sayHello need to do something sayHello.addActionListener(new MyActionListener()); } private class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (!checkbox.isSelected()) { JOptionPane.showMessageDialog(null, "I do not like you, " + firstName.getText() + " " + lastName.getText() + "!"); } else { JOptionPane.showMessageDialog(null, "How are you, " + firstName.getText() + " " + lastName.getText() + "?"); } } } }
Create also the
MainTester
               class
               and run this class as Java application.
               
            package com.vogella.javaintroduction.swing; public class MainTester { public static void main(String[] args) { MyFirstUI view = new MyFirstUI(); view.setVisible(true); } }
You should see the following. A mesage dialog should be seen if you press the button.
Java allows to schedule tasks. A scheduled tasks can performs
               once
               or several times. 
               
            
java.util.Timer and java.util.TimerTask can be used to schedule tasks. The object which implements TimeTask will then be perform by the Timer based on the given interval.
java.util.Timer and java.util.TimerTask can be used to schedule tasks. The object which implements TimeTask will then be perform by the Timer based on the given interval.
package schedule; import java.util.TimerTask; public class MyTask extends TimerTask { private final String string; private int count = 0; public MyTask(String string) { this.string = string; } @Override public void run() { count++; System.out.println(string + " called " + count); } }
package schedule; import java.util.Timer; public class ScheduleTest { public static void main(String[] args) { Timer timer = new Timer(); // wait 2 seconds (2000 milli-secs) and then start timer.schedule(new MyTask("Task1"), 2000); for (int i = 0; i < 100; i++) { // wait 1 seconds and then again every 5 seconds timer.schedule(new MyTask("Task " + i), 1000, 5000); } } }

Comments
Post a Comment