Friday 10 March 2017

Introduction to Java Programming



Introduction to Java Programming


Revision History
Revision 0.1 - 0.6
07.08.2008
Lars Vogel
First Versions
Revision 0.7
22.10.2009
Lars Vogel
Moved Date and Time API to own article
Revision 0.8
30.12.2009
Lars Vogel
Clarification JVM and JRE
Revision 0.9
12.01.2010
Lars Vogel
Type conversion improved
Introduction to Java programming
This article explains the Java programming language, create a few small programs, discuss Java design principles and describes a few common solutions to commons problems. It also contains "Cheat Sheets" with examples for standard tasks during programming.
This article contains lots of exercises. The solutions for these exercises are available under http://www.vogella.de/code.html .
This article does not cover the installation of the Java Development Kit (JDK).

Table of Contents

1. Introduction


1.1. History

Java is a programming language created by James Gosling from Sun Microsystems in 1991. The first public available version of Java (Java 1.0) was released 1995. Over time several version of Java were release which improved and enhanced the language and it libraries. The current version of Java is Java 1.6 also known as Java 6.0. Java is a de facto standard that is controlled through a standard process, called the Java Community Process.
From the Java programming language the Java platform evolved. The Java platform allows that Code is written in other languages then the Java programming language and still runs on the Java virtual machine.

1.2. Overview

The Java programming language consists out of a Java compiler, the Java virtual machine, and the Java class libraries. The Java virtual machine (JVM) is a software implementation of a computer that executes programs like a real machine.
The Java compiler translates Java coding into so-called byte-code. The Java virtual machine interprets this byte-code and runs the program.
The Java virtual machine is written specifically for a specific operating system.
The Java runtime environment (JRE) consists of the JVM and the Java class libraries.

1.3. Characteristics of Java

The target of Java is to write a program once and then run this program on multiple operating systems.
Java has the following properties:

·         Platform independent: Java program do in general not access directly system resources but use the Java virtual machine as abstraction. This makes Java programs highly portable. A Java program which is standard complaint and follows certain rules can run unmodified all several 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. types of the elements must be pre-defined and conversion to other objects is relatively restricted.

·         Interpreted and compiled language: Java source code is transfered into byte-code which does not depend on the target platform. This byte-code will be interpreted by the Java Virtual machine (JVM). The JVM contains a so called Hotspot-Compiler which translates critical byte-code into native code.

·         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 object to which no active pointer exists.
The Java syntax is similar to C++. Java is case sensitive, e.g. the variables myValue and myvalue will be treated as different variables.

1.4. Development with Java

The programmer writes java source code which can be done in any text editor which supports plain text as output. Normally the programmer uses an IDE (integrated development environment) for programming. An IDE support usually the programmer in his tasks, e.g. it provides auto-formatting of the source code, highlighting of the important keywords, etc.
At some point the programmer (or the IDE) calls the java compiler. The java compiler creates platform independent code which is called bytecode.
Bytecode can be executed by the java runtime environment. The java runtime environment (JRE) is a program which knows how to run the bytecode on the operating system. The JRE translates the bytecode into native code, e.g. the native code for Linux is different then the native code for Windows and executes it.
The classpath is the connection between the Java compiler and Java interpreter. It defines where the compiler and interpreter look for .class files to load.
By default, the compiler puts each class file in the same directory as its source file. You can specify a separate destination directory with -d

2. Classpath

The classpath in Java defines which java class are available. 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 your program.

3. Your first Java program


3.1. Write source code

The following Java program is developed under Microsoft Windows. The process on other operating system should be similar but will not be covered here. Select a directory which should contain your code. I will use the directory c:\temp\java which I will as of now call javadir.
Open a text editor which supports plain text, e.g. notepad under Windows and write the following source code. You can start notepad via Start->Run-> notepad and pressing enter.

                               
// The smallest Java program possible
public class HelloWorld {
        public static void main(String[] args) {
               System.out.println("Hello World");
        }
}
 
                       

Save the source code in your directory javadir under the name "HelloWorld.java".

Tip


The name of a Java source file must always equal the class name and end with .java. In our case the filename must be HelloWorld.java because the class is called HelloWorld.

3.2. Compile the code

Switch to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the javadir directory with the command cd javadir, for example in my case cd c:\temp\java. Use the command dir to see that the source file is in the directory.
Type javac HelloWorld.java .
Check the content of the directory with the command "dir". The directory contains now a file "HelloWorld.class".
Congratulations you compiled your first java source code.

3.3. Run the code

Switch again to the command line, e.g. under Windows Start-> Run -> cmd. Switch to the directory jardir.
Type java HelloWorld .
The system should write "Hello World" on the command line.

3.4. Using the classpath

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 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
Type java -classpath "mydirectory" HelloWorld . Replace "mydirectory" with the directory which contains the test directory. You should again see the "HelloWorld" output.

4. Integrated Development Environment

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, e.g. Netbeans and IntelliJ .
For an introduction on how to use the Eclipse IDE please see Using Eclipse as IDE - Tutorial .
In the following I will say "Create a Java project SomeName". This will refer to creating an Eclipse Java project. If you are using a different IDE please follow the required steps in this IDE.

5. Your first graphical user interface application (GUI)

5.1. Create a Java Project

The following will use Eclipse as a development environment. See Using Eclipse as IDE - Tutorial for an introduction on how to use the Eclipse IDE. See Create your first Java program under Eclipse for creating a simple Java project.
Create a new Java project "JavaIntroductionUI".

5.2. Code

Create the following class MyFirstUI.java in package ui.
                               
package ui;
 
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() {
 
               // Lets make it look nice
               // This you can ignore / delete if you don't like it
               // try {
               // for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
               // if ("Nimbus".equals(info.getName())) {
               // UIManager.setLookAndFeel(info.getClassName());
               // break;
               // }
               // }
               // } catch (Exception e) {
               // e.printStackTrace();
               // }
 
               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 don't like you, "
                                              + firstName.getText() + " " + lastName.getText() + "!");
                       } else {
                               JOptionPane.showMessageDialog(null, "How are you, "
                                              + firstName.getText() + " " + lastName.getText() + "?");
                       }
               }
 
        }
}
 
                       
Create also the following class MainTester.java in package test and start this class.
                               
package test;
 
import ui.MyFirstUI;
 
public class MainTester {
        public static void main(String[] args) {
               MyFirstUI view = new MyFirstUI();
               view.setVisible(true);
        }
}
 
                       

5.3. Result

You should see the following. A mesage dialog should be seen if you press the button.

6. Object Oriented Programming Principles

The following is a short summary of object oriented programming principles which apply for most object oriented programming languages.

6.1. Encapsulation

In general a general manipulation of an object's variables by other objects or classes is discouraged to ensure data encapsulation. A class should provide methods through which other objects could access variables. Java deletes objects which are not longer used (garbage collection).

6.2. Abstraction

Java support the abstraction of data definition and concrete usage of this definition.
The concept is divided from the concrete which means you first define a class containing the variables and the behavior (methods) and afterwards you create the real objects which then all behave like the class defined it.
A class is the definition of the behavior and data. A class can not be directly be used.
A object in an instance of this class and is the real object which can be worked with.

6.3. Polymorphisms

The ability of object variables to contain objects of different classes. If class X1 is a subclass of class X then a method which is defined with a parameter for an object X can also get called which an object X1.
If you define a supertype for a group of classes any subclass of that supertype can be substituted where the supertype is expected.
If you use an interface as a polymorphic type any object which implements this interface can be used as arguments.

6.4. Inheritance

Inheritance allows that classes can be based on each other. If a class A inherits another class B this is called "class A extends class B".
For example you can define a base class which provides certain logging functionality and this class is extended by another class which adds email notification to the functionality.

7. Definitons

It is important to understand the base structure of packages, classes and objects.

7.1. Basics: Package, Class and Object

7.1.1. Package

Java groups classes into functional packages. All classes in java.lang are automatically available in the java programs.
The main reason of packages is to avoid naming collisions. One programmer may create a java class Test. Another program may create another class with the same name. With the usage of packages you can tell the system which class to call. For example if programmer 1 put the class test into package programmer1 and the second programmer puts his class into package "xmlreader" and you would like to access the second class you can do this via xmlreader.Test.
The other important reason is that via packages you can group your classes into logical units.

7.1.2. Class

Def.: Template that describes the data and behavior associated with an instance of that class.
The data associated with a class is stored in variables; the behavior associated to a class or object is implemented with methods.
Can be seen as the blueprint of object.
A class
·         Is defined by the keyword class
·         Start with a capital letter
·         Body of a class is surrounded by {}

7.1.3. Object

Def.: An object is an instance of a class.
While a class can be considered as a blueprint for the data and the behavior of an object the object is the real element which has data and can perform actions.
For example as class may be the blueprint of a car, an object is then a real car.
Every object extends implicitly the Object “Object” and get wherefore gets the methods defined by class Object
·         o.equals(o1) Is the Object equal to o1
·         o.getClass() Returns the class of o
·         o.hashCode() Returns a unique ID o.toString()

7.2.  Variables


7.2.1. Variable

Variable can either be a primitive 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 then you compare if both point to the same object. To compare objects use object1.equals(object2).

7.2.2. Instance variable

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 transisient. Instance variables marked as final can not be changed after assigned to a value.

7.2.3. Local Variable

Local (stack) variable declarations cannot have access modifiers.
final is the only modifier available to local variables
Local variables don't get default values, so they must be initialized before use.

7.3. Modifiers

7.3.1. Access Modifiers

There are three access modifiers: public, protected and private
There are four access levels: public, protected, default and private
protected and default are similar. Only difference: A protected class can get accessed from the package and sub-classes outside the package while a default class can get only access via the same package protected = package plus kids

7.3.2. Other modifiers

final methods: cannot be overwritten in a subclass
abstractmethod: no method body
synchronized method: threat safe, can be final and have any access control
native methods: platform dependent code, apply only to methods
stricttp: class or method

7.4. Interface

Within java an interface is a type just as a class is a type. Like a class an interface defines methods.
Interfaces are contracts for what a class can do but they say nothing about the way in which the class must do it.
Interfaces are per default public and abstract – explicit declaration of these modifiers is optional.
An interface can also have abstract methods, no concrete methods are allowed.
Interfaces can have constants which are always implicitly public, static and final.

7.5.  Additional Definitions

7.5.1. Method

A method can trigger a certain action.
Method with var-args: 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 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.

7.5.2. Constructor

classname (Parameter p1, ..) {}
The constructor is always called if the class is created. 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.

7.5.3. Class method or class variable

Class method / variable is associated with the class and not the instance. To refer to it use the classname and the class method / variable together with a period ("."). Example System.out.println("Hello World"). The runtime environment associates one class variable for a class no matter how many instances exists.
Class method / variant does exists once for all instances. They are indicated with the word static. If a variable should be existing for all instances and be non-changeable (=CONSTANT) then also the word final is used.
The static method runs without any instance of the class. Does not depend on instance (non-static) variables. Can not use the this object or an instance variables.
The static variable is the same of all instances of the class (global variable)

7.5.4. Abstract class

If a class has one method which only contain the declaration of the method but not the implementation then this class is abstract and can not be initialized. Sub-classes need then to define the methods except if they also declared as abstract. method abstract double returnDouble();
If a class contains an abstract method it also needs to get defined as abstract.

8. Statements

The following describes certain aspects of the software.

8.1. Boolean Operations

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.
Table 1. 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

8.2. Switch Statement

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;
                               }
                       }
                       

9. Working with Strings

The following lists the most common string operations.
Table 2. 
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 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.

10. I/O (Input / Output) handling

10.1. Overview

The java package java.io contains classes which can be used to read and write to files and other sources. In general the classes in this package can be divided into the following classes:
·         Connection Streams: Represents connections to destinations and sources such as files or network sockets. Usually low-level.
·         Chain Streams: Work only if chained to other stream. Usually higher level protocol.

10.2. Read or write a text file

The following class "MyFile" contains methods for reading and writing a text file.
                               
package test;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
public class MyFile
{
 
        public String readTextFile(String fileName)
        {
               String returnValue = "";
               FileReader file;
               String line = "";
               try
               {
                       file = new FileReader(fileName);
                       BufferedReader reader = new BufferedReader(file);
                       while ((line = reader.readLine()) != null)
                       {
                               returnValue += line + "\n";
                       }
               } catch (FileNotFoundException e)
               {
                       throw new RuntimeException("File not found");
               } catch (IOException e)
               {
                       throw new RuntimeException("IO Error occured");
               }
               return returnValue;
 
        }
 
        public void writeTextFile(String fileName, String s)
        {
               FileWriter output;
               try
               {
                       output = new FileWriter(fileName);
                       BufferedWriter writer = new BufferedWriter(output);
                       writer.write(s);
               } catch (IOException e)
               {
                       e.printStackTrace();
               }
 
        }
}
 
                       

11. Collection

A collection is a data structure which is used to contain and process sets of data. The data is encapsulated and the access to the data is only possible via predefined methods.
For example if your applications saves data in the object People you can store different People objects about people in a collection.

Tip

While arrays are fixed sized, collections have a dynamic size, e.g. a collection can contain a flexible number of object.
When you need elements of various types or a dynamically changing number of them you use Java Collections.
Typical collections are: stacks, queues, deques, lists and trees.
As of Java 5 collections should get parameterized with an object declaration to enable the compiler to check if objects which are added to the collection have the correct type.
                       
package collections;
 
import java.util.ArrayList;
 
public class MyArrayList {
 
        public static void main(String[] args) {
               // Declare the ArrayList
                ArrayList<String> var = new ArrayList<String>();
               // Add a few Strings to it
               var.add("Lars");
               var.add("Jennifer");
               // Loop over it and print the result to the console
               for (String s : var) {
                       System.out.println(s);
               }
        }
}
 
               
java.util.Collections is the basis class which provides you useful functionality.
Table 3. Sample Table
Collections.copy(list, list)
Copy a collection to another
Collections.reverse(list)
Reserve the order of the list
Collections.shuffle(list)
Shuffles the list
Collections.sort(list)
Sort the list

12. Type Conversion

If you use variables of different types Java requires for certain types an explicit conversion. The following gives examples for this conversion.

12.1. Conversion to String

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"
                       

12.2. Conversion from String to Number

                               
// 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;
        }
                       

12.3. Double to int

int i = (int) double;

12.4. SQL Date conversions

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();
        }        
 
}
 
                       

13. JAR files - Java Archive

13.1. What is a jar

A JAR file is a Java Archive based on the pkzip file format. A jar files can contain java classes and other resources (icons, property files) and can be executable.
JAR files are the deployment format for Java. You can distribute your program in a jar file or you can use exiting java code via jars by putting them into your classpath.

13.2. Executable jar

An executable JAR means the end-user doesn't have to pull the class files out before running the program. This is done via a manifest.txt file which tells the JVM which class has the main() method. The content of the manifest.txt file:
 Manifest-Version: 1.0 Main-Class: MyApp Class-Path:
                               . lib/jcommon-1.0.6.jar lib/itext-1.4.6.jar "Empty Line"
                       
A empty line is required otherwise the jar will be executable. Space after a new line is also required
To create one executable JAR file run on the command line
 jar -cvmf mainfest.txt app1.jar *.class
                       

14. Cheat Sheets

The following can be used as a reference for certain task which you have to do.

14.1. Working with classes

While programming Java you have to create several classes, methods, instance variables. The following uses the package test.
Table 4. 
What to do
How to do it
Create a new class called "MyNewClass".
                                                                        
package test;
 
public class MyNewClass {
 
}
 
                                                                
Create a new attribute (instance variable) "var1" in MyNewClass with type String
                                                                        
package test;
 
public class MyNewClass {
        private String var1;
}
 
                                                                
Create a Constructor for "MyNewClass 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 "doSomeThing" in class which do 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 "doSomeThing2" in class which do 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 "doSomeThing2" in class which do return 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 "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;
        }
}
 
                                                                

14.2. Working with local variable

A local variable must always be declared in a method.
Table 5. 
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>();

15. Exercises

15.1.  Exercise 02: Naming conventions

Remember the class names should always start with a large letter, e.g. class Test

Tip

You can rename classes in Eclipse via F2 in the package explorer or via selecting the class in the source code and right mouse click -> Refactor -> Rename.
Remember that variable names should always start with a small letter, e.g. int zahl.

Tip

You can rename variables in the complete source code selecting the variable in the source code and right mouse click -> Refactor -> Rename
Activate the automatic source code formating at save. Select Windows -> Preferences. Select then Java -> Editor -> Save Actions and make the following settings.

15.2. Exercise 04 - Creating a simple Person Java classes

Task: Create two classes. Use basis string concatenation, use the for loop.
Create the package "exercises.exercise02". Create a class "Person" with the following code.
                               
package exercises.exercise04;
 
class Person {
        String firstname = "Jim";
        String lastname = "Knopf";
        int age = 12;
 
        void writeName() {
               System.out.println(firstname + " " + lastname + "" + age);
        }
 
}
 
                       
Create a class "Main" with the following source code.
                               
package exercises.exercise04;
 
public class Main {
        public static void main(String[] args) {
               Person person = new Person();
               person.writeName();
        }
}
 
                       
Tasks / Questions:
·         Run the code and review the result.
·         Create a second class for a second person and write the other name.

15.3. Exercise 06 - Enhance your Person Java classes with a constructor

Task: Develop a constructor for your Person class.
Create the package "exercises.exercise06". Copy your class "Person" to this package and create a constructor
                               
package exercises.exercise06;
 
class Person {
        int age = 12;
        String firstName;
        String lastName;
 
        public Person(String a, String b) {
               firstName = a;
               lastName = b;
        }
 
        void writeName() {
               System.out.println(firstName + " " + lastName + "" + age);
        }
}
 
                       
Create another class Main and create two person.
                               
package exercises.exercise06;
 
public class Main {
        public static void main(String[] args) {
               Person person = new Person("Jim", "Knopf");
               person.writeName();
               Person person = new Person("Henry", "Ford");
               person.writeName();
        }
}
 
                       

15.4. Exercise 08 - Return values

Create package exercises.exercise08.
Write a Class "Math" which performs the following:
·         method multiply (int a, int b) - returns a * b;
·         method add (int a, int b) - returns a + b;
·         method substract (int a, int b) - returns a - b;
·         method divide (int a, int b) - returns a / b ; Pay attention to the return type here!
Write a class Main which tests each method and writes the result to the console. The test class could look like the following.
                               
package exercises.exercise08;
 
public class Main {
        public static void main(String[] args) {
               Math math = new Math();
               System.out.println(math.multiply(5, 2));
               System.out.println(math.add(8, 2));
               System.out.println(math.substact(5, 2));
               System.out.println(math.divide(5, 2));
        }
}
 
                       

15.5. Exercise 10 - Enhance your Person Java classes with getter and setter

Task: Develop a constructor for your Person class.
Create the package "exercises.exercise10". Create a class "Person" with the following code.
                               
package exercises.exercise10;
 
public class Person {
        // We define two variables for the first and last name
        // String is the type of the variable
        private String firstName;
        private String lastName;
 
        // This is the constructor of the class it expects two variables:
        // firstName
        // lastName
        public Person(String firstName, String lastName) {
               // the keyword "this" allows to refer to variables of the class.
               // It allows to distinguish between the variables which are passed
               // into the constructor and the variables of the class
               this.firstName = firstName;
               this.lastName = lastName;
        }
 
        public void setFirstName(String s) {
               firstName = s;
        }
 
        public void setLastName(String s) {
               lastName = s;
        }
 
        public String getFirstName() {
               return firstName;
        }
 
        public String getLastName() {
               return lastName;
        }
}
 
                       
Create a class "Main" with the following source code.
                               
package exercises.exercise10;
 
// This class defines the main method and nothing else
// The "real" object is person
public final class Main {
        private Main() {
        }
 
        /**
         * @param args
         */
        public static void main(String[] args) {
               Person person = new Person("Jim", "Knopf");
               Person person2 = new Person("Jill", "Sanders"");
               // Jill heiratet Jim
               person2.setLastName("Knopf");
               
        }
}
 
                       

15.6. Exercise 12 - Create an Address Class and use it in the person

Task: Create an address class with the following fields:
·         Street
·         Number
·         PostalCode
·         City
·         Country
Write setter and getter for the address. Each person should have an address. Add a field "address" to the person.

15.7. Exercise 14 - Write a Beer Class

Task: We want to calculate the alcohol concentration of a person. Create an Beer class with the following fields:
·         Name
·         PercentageAlcohol - This field will store the information 0,48 for 4, 8%
·         Quantity - This field will store the quantity in ml (333 for a standard beer)
Write setter and getter for both fields. Write a method which calculates the quantity of alcohol in a beer based on the following formula: Quantity * 0,8 (fixed factor for the density of alcohol) * PercentageAlcohol

15.8. Exercise 16 - Wrap-it up

As of now you should have created a Person class and a Address class. This exercise tries to ensure that everyone has a simular solution.
Create a new package exercises.exercise16
Copy to / re-create your class Person in the package exercises.exercise16. This class should be similar to to following code:
               
package exercises.exercise16;
 
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 exercises.exercise16;
 
public class Person {
        private String firstName;
        private String lastName;
        private int age;
        private Address address;
 
        // Constructor
        public Person(String firstName, String lastName) {
               this.firstName = firstName;
               this.lastName = lastName;
        }
 
        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;
        }
 
        public String toString() {
               return firstName + " " + lastName + " " + age;
        }
}
 
        

Tip

You have create a Person and Address class but you have not created any objects yet.
Create a new class Tester with a main method which will use the created classes.
               
package exercises.exercise16;
 
public class Tester {
 
        public static void main(String[] args) {
               // I create a person
               Person pers = new Person("Jim", "Knopf");
               // 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 don't
                * 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 don't need address any more
               address = null;
 
               // person is moving to the next house in the same street
               pers.getAddress().setNumber("105");
 
        }
 
}
 
        

15.9. Exercise 20 - Write an if statement

Task: Write a main program which creates a random number between 0 - 100 and asked the user if the number is higher then 50 or less then 50. If the user did ask right then write "Very well, you did it!" to the console, otherwise write "You are a loooooser!" to the console.
Create package exercise20 for this exercise.
Create the following class. This is a helper class you will use for reading input from the command line.

Tip

At this point in time you don't need to understand this class.
               
package exercises.exercise20;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/*
 * This class will read an line from the command line
 * and return it from the caller
 */
public class ReadInput {
        public String readLine() {
               InputStreamReader converter = new InputStreamReader(System.in);
               BufferedReader in = new BufferedReader(converter);
               // We will later learn want a try / catch block is
               try {
                       String userInput = in.readLine();
                       return userInput;
               } catch (IOException e) {
                       e.printStackTrace();
                       return "failed";
               }
        }
}
 
        
Copy the program from below and try to understand if statement if part of it.
               
package exercises.exercise20;
 
// We will later learn want a import mean
import java.util.Random;
 
public class Main {
        public static void main(String[] args) {
               String userInput = "";
               Random random = new Random();
               // Create a number between 0 and 100
               int nextInt = random.nextInt(101);
               ReadInput in = new ReadInput();
               System.out.println("Do you think the number is larger then 50?");
               userInput = in.readLine();
               if (userInput.equalsIgnoreCase("y") && nextInt > 50) {
                       System.out.println("Very well, you did it!");
               } else {
                       System.out.println("You are a loooooser!");
               }
               System.out.println("The number was " + nextInt);
        }
}
 
        

15.10. Exercise 22 - Write an while statement

Task: Write a main program which creates a random number between 0 - 100. The user must guess the number until we has found the correct answer.
Create package exercise22 for this exercise.
This is a helper class for reading has been improve to read an integer from the command line. Use this class. Your task is then to write the main method for the game.
               
package exercises.exercise22;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/*
 * This class will read an line from the command line
 * and return it from the caller
 */
public class ReadInput {
        public String readLine() {
               InputStreamReader converter = new InputStreamReader(System.in);
               BufferedReader in = new BufferedReader(converter);
               // We will later learn want a try / catch block is
               try {
                       String userInput = in.readLine();
                       return userInput;
               } catch (IOException e) {
                       e.printStackTrace();
                       return "failed";
               }
        }
 
        public int readInteger() {
               String in = readLine();
               try {
                       // Translate string to integer
                       return Integer.parseInt(in);
               } catch (NumberFormatException e) {
                       // In case we did not get a number return zero
                       return 0;
               }
 
        }
}
 
        

15.11. Exercise 24 - Arrays and for loops

Task: Create a class TestArray with declares an array which can store 2 persons. Store 2 persons in this array and use a for loop to write the first name to the console.
               
package exercises.exercise24;
 
public class TestArray {
        public static void main(String[] args) {
               Person personArray[] = new Person[2];
               Person person = new Person("Lars", "Vogel");
               personArray[0] = person;
               person = new Person("Jim", "Knopf");
               personArray[1] = person;
 
               for (int i = 0; i < personArray.length; i++) {
                       // Print the first name of the person
                       System.out.println(personArray[i].getFirstName());
               }
        }
}
 
        

15.12. Exercise 26 - Reading a text file

Task: Read a text file which contains a list of persons. Use an editor for this which does save the information as plain text, e.g. notepad.
For example the file might look like:
                       
Lars,Vogel
Jim,Knopf
Hendrik,Test
 
               
Save it on your file system, e.g. on c:\temp\person.txt
Use the class from the following description: Reading and Write to text Files.

Tip

In Java the best way of specifying a pathname is using the slash /. Alternatively can you use the \\ For example call the the method with the following code:
                       
MyFile file = new MyFile();
file.readTextFile("c:/temp/person.txt");
file.readTextFile("c:\\temp\\person.txt");
 
               
Write a main program which reads this file and writes the content to the console.

15.13. Exercise 28 - Reading a text file - Split the input

Extent your example from exercise 26 so that the first name and the last name a written into a separate line.

Tip

You can split a string with the available method .split(","). See See Working with strings.

15.14. Exercise 30 - Reading a text file - Split the input and create an ArrayList / Array

Extent your example from exercise 28 so that new object of type Person is created for each line. Save all persons in an array or in an ArrayList. Print to the console the total number of all persons.

15.15. Exercise 32 - String operations

Extent exercise 30. Loop over your array and find out if you have a person in your ArrayList / array where the first name starts with J and the last name starts with K.

15.16. Exercise 38 - Write a TaxCalculator

Task: Write a program which calculates the tax for a person based on the german system.
Create package exercise30 for this exercise. Copy your Person and Address class into this package.
Extend your Person class so that a person has also an income field. Create setter and getter for this field.
The German income tax is calculated the following (see wikipedia):
·         Until 7.664 € -> no taxes
·         Between 7665 € and 12739 € -> StB = (883,74 * y + 1500) * y . With y being (income - 7664) / 10000.
·         Between 12.740 € and 52.151 € StB = (228,74 * z + 2.397) * z + 989 . With z being (income - 12739) / 10000.
·         Between 52.152 € and 250.000 € -> StB = 0,42 * income − 7914 .
·         Over 250.001 € -> StB = 0,45 * income − 15 414 .
Task: Write a class TaxCalculator with the following method: public float calculateTax(Person person). This method should calculate the tax for a give person. Write also a main method which tests this class.

15.17. Exercise 40 - Memory Management

Task: Understand automatic memory management.
Java provides automatic memory management. This does not mean that you have infinite memory. Java will release all memory which is not used anymore but the Java application will crash if you request more memory from the system then is available for the Java application.
Create the package "exercises.exercise20" and the following classes. Check if you get an out-of-memory situation.
                               
package exercises.exercise20;
 
public class MinMax {
        private int min = 0;
        private int max = 0;
 
        public int getMin() {
               return min;
        }
 
        public void setMin(int min) {
               this.min = min;
        }
 
        public int getMax() {
               return max;
        }
 
        public void setMax(int max) {
               this.max = max;
        }
 
}
 
                       
                               
package exercises.exercise20;
 
import java.util.ArrayList;
 
public class TestCreateObjects {
        private static final long MAX = 10000000;
 
        public void create() {
               System.out.println("First only the objects");
               for (long i = 0; i <= MAX; i++) {
                       MinMax object = new MinMax();
                       object.setMin(100);
                       object.setMin(200);
                       if ((i % 100000) == 0) {
                               System.out.println("Number of objects " + i);
                       }
               }
        }
 
        public void createList() {
               System.out.println("Now the list");
               ArrayList<MinMax> list = new ArrayList<MinMax>();
               for (long i = 0; i <= MAX; i++) {
                       MinMax object = new MinMax();
                       object.setMin(100);
                       object.setMin(200);
                       list.add(object);
                       if ((i % 100000) == 0) {
                               System.out.println("Number of objects " + i);
                       }
               }
        }
}
 
                       
                              
package exercises.exercise20;
 
public final class Main {
        // Avoid that someone creates an instance of this class
        private Main() {
        }
 
        /**
         * @param args
         */
        // This will
        public static void main(String[] args) {
               TestCreateObjects test = new TestCreateObjects();
               // Will we get a out-of-memory error?
               test.create();
               // Will we get a out-of-memory error?
               test.createList();
        }
}
 
                       

16. Thank you

If you like this tutorial please support this website. 




No comments:

Post a Comment