1 © Luxoft Training 2012 Java basics Module 2
2 © Luxoft Training 2012 Running Java application
3 © Luxoft Training 2012 The class is declared: Class description defines class visibility, i.e. classes of which packages can access this class The public modifier defines that such a class can be accessed anywhere. Only one public class can be defined in a file. class { }
4 © Luxoft Training 2012 The main() method is an entry point for any Java program (application). The simplest application is composed of one method main. To run an application in JVM, type in the java command line: Class description Note! If the class does not have main or its signature is wrong an error java.lang.NoSuchMethodError is generated
5 © Luxoft Training 2012 The main method signature. Method signature public static void main(String[] args) void – return type. args – a list of command line arguments. The main method should be declared as static. Static method may be (and must be) invoked as: TheClass.staticMethod(...) Note! Program running time equals the main() method execution time.
6 © Luxoft Training 2012 Class example
7 © Luxoft Training 2012 Exercises Analyzing and initiating the first Java application. Developing application with two classes.
8 © Luxoft Training 2012 The classpath concept Java program is a chain of methods invocations of certain object classes. Therefore, during compilation and program runtime the information about the location of byte code of needed classes is required. When launching the javac program that compiles java file, you can specify a path list for local file system where dependent classes can be found. This specification of paths is called classpath.
9 © Luxoft Training 2012 The classpath concept Directories in Windows are separated by ;, in Unix by : If compiled Person.java java file uses some compiled classes located in c:\lib\classes it is necessary to indicate the path for compiler through classpath flag. javac -d bin -sourcepath src -classpath C:\lib\classes Person.java
10 © Luxoft Training 2012 The classpath concept Similarly, classpath can be specified when launching java application. JVM will lookup required classes in specified paths. java -classpath C:\lib\classes Test Note! You can avoid compiling each class separately if you indicate file with main class for compiler.
11 © Luxoft Training 2012 JVM has a special loader (bootstrap class loader) that is able to load class byte code from file system taking into account full class name. Class loading
12 © Luxoft Training 2012 Compiling and running
13 © Luxoft Training 2012 Packages Packages are used to organize classes. Just like two different readme.txt files can be located in different directories, java classes can be located in different directories as well. Packages allow to avoid collisions when classes have the same name.
14 © Luxoft Training 2012 Packages To place HelloWorld.java file into the world package it is necessary to specify package name in the file with the help of keyword package. Package declaration should be the first statement. To execute this class its necessary to go to the base directory src and type: $ java –classpath. world.HelloWorld // only comment can be here package world; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); }
15 © Luxoft Training 2012 Packages To use a class located in some package you should specify its full name: package another; import world.HelloWorld; public class Test { public static void main(String[] args) { HelloWorld instance = new HelloWorld(); } package another; public class Test { public static void main(String[] args) { world.HelloWorld instance = new world.HelloWorld(); } Another possibility is to import class:
16 © Luxoft Training 2012 Packages package org.jboss.tools.example.data; public class MemberRepository { … } package org.jboss.tools.example.data; public class MemberListProducer { // MemberRepository can be used without import // because its located in the same package } package org.jboss.tools.example.model; // other package – class should be imported import org.jboss.tools.example.data.MemberRepository; public class Member { … }
17 © Luxoft Training 2012 Import Class import have nothing to do with loading imported class and doesnt affect the compilation and running time. We can also include all classes of the given package to namespace: import package.subpackage.*;
18 © Luxoft Training 2012 Jar archives There is a way to organize classes in zip archive for more convenient propagation of the.class file group The archive has.jar extension If classes are located in JAR file, it is necessary to specify the archives file name in classpath. java –classpath c:\libs\myjar.jar thepackage.MainClass
19 © Luxoft Training 2012 Jar archives To create Jar file: jar.exe cf myjar.jar MainClass.class c – creates Jar file f – specifies fine name
20 © Luxoft Training 2012 Jar archives You can also manually define special manifest file in a JAR file that describes this JAR file. The manifest is stored in META-INF archive directory By default, it is created by jar tool
21 © Luxoft Training 2012 Jar archives For example, manifest can indicate class name that contains main(): In this case JVM can be launched as follows: Manifest-Version: 1.0 java -jar MyJar.jar Class-Path: ojdbc14.jar Created-By: Eclipse Main-Class: MyPackage.MyClass
22 © Luxoft Training 2012 Exercise Working with packages and Jar files
23 © Luxoft Training 2012 Primitive types
24 © Luxoft Training 2012 Primitive types
25 © Luxoft Training 2012 Logic primitive types The boolean data type has only two possible values : true or false The actual size can vary in different JVM boolean b1 = true; boolean b2 = false; Note! boolean cannot be cast to any type. The opposite is true as well.
26 © Luxoft Training 2012 Primitive data types casting The scheme of widening conversion: byte short char int long float double All other conversions are narrowing – you should use explicit casting: double d = 5; int i = (double)d;
27 © Luxoft Training 2012 Primitive data types By default, numeric literal is a int type value or double type value. However, the following is possible: byte b = 1; short s = 2; char c = 3; float а = 1.234; // Error Note! Compiler checks the literal and if its in the allowable range, allows for assignment
28 © Luxoft Training 2012 Object references
29 © Luxoft Training 2012 Object references
30 © Luxoft Training 2012 Life on the garbage-collectible heap
31 © Luxoft Training 2012 Life on the garbage-collectible heap Book d = c; Book b = new Book(); Book c = new Book(); b = c; c = null;
32 © Luxoft Training 2012 Arrays
33 © Luxoft Training 2012 Arrays of primitives
34 © Luxoft Training 2012 Array of objects
35 © Luxoft Training 2012 Array of objects
36 © Luxoft Training 2012 Java & C++ arrays In C++, when you declare an array, storage for the array is allocated. In Java, when you declare an array, you are really only declaring a pointer to an array; storage for the array itself is not allocated until you use "new": C++ int A[10]; // A is an array of length 10 A[0] = 5; // set the 1st element of array A JAVA int [] A; // A is a pointer to an array A = new int [10]; // now A points to an array of length 10 A[0] = 5; // set the 1st element of the array pointed to by A
37 © Luxoft Training 2012 Java & C++ arrays In Java, a default initial value is assigned to each element of a newly allocated array if no initial value is specified. The default value depends on the type of the array element: In Java, an out-of-bounds array index always causes a runtime error. In Java, you can determine the current length of an array (at runtime) using ".length": int [] a = new int[10];... a.length... // this expression evaluates to 10 a = new int[20];... a.length... // now it evaluates to 20
38 © Luxoft Training 2012 Using ArrayList
39 © Luxoft Training 2012 Java operators
40 © Luxoft Training 2012 Java operators
41 © Luxoft Training 2012 The + operator with strings
42 © Luxoft Training 2012 instanceof operator The instanceof operator tests object class in runtime. Left operand is a reference to an arbitrary object. Right operand is a class, interface or an array. Object o = new String(aaa); if (o instanceof String) { System.out.println(It's a String); }
43 © Luxoft Training 2012 instanceof operator instanceof operator can be used to test if an object is of a specified type:
44 © Luxoft Training 2012 Continue and break with the label
45 © Luxoft Training 2012 OOP in Java
46 © Luxoft Training 2012 Local and instance variables
47 © Luxoft Training 2012 Java Beans public class Clock { private String time; public void setTime(String time) { time = this.time; } public String getTime() { return time; } class ClockTestDrive { public static void main(String [] args) { Clock c = new Clock(); c.setTime("1245"); String tod = c.getTime(); System.out.println("time: " + tod); }
48 © Luxoft Training 2012 Access modifiers: Access modifiers public protected default (friendly, package) private Only one modifier can be used: class Parser {…} public class EightDimensionalComples { … } private int i; protected double getChiSquared() {…} private class Horse {…} default Button getBtn(){…}
49 © Luxoft Training 2012 Access modifiers When overriding a method you cant make its scope less visible. Visibility scope of overridden method can be the same as visibility scope of an overriding method or even higher.
50 © Luxoft Training 2012 Using polymorphism
51 © Luxoft Training 2012 Absract classes
52 © Luxoft Training 2012 Multiple inheritance
53 © Luxoft Training 2012 Using interfaces Classes from different inheritance trees can implement the same interface.
54 © Luxoft Training 2012 public interface Pet { public abstract void beFriendly(); public abstract void play(); } public class Dog extends Canine implements Pet { public void beFriendly() {...} public void play() {...} public void roam() {...} public void eat() {...} } Using interfaces Better still, a class can implement multiple interfaces: public class Dog extends Animal implements Pet, Saveable, Paintable {... }
55 © Luxoft Training 2012 Interfaces Interface forms a contract between the clients code and a class that implements this interface. An interface may be considered as an abstract class whose methods are all abstract. Java interface is declared with the interface keyword. A class that implements an interface contains the implements clause in the class declaration.
56 © Luxoft Training 2012 Interfaces
57 © Luxoft Training 2012 Interfaces As long as an interface is a specification of certain behavior, the class can implement several interfaces:
58 © Luxoft Training 2012 Interfaces
59 © Luxoft Training 2012 Interfaces As long as an interface is a contract rather than an implementation: It cannot be instantiated There are no constructors There is no instance data Note! An interface can contain static final data
60 © Luxoft Training 2012 Interfaces The public static final modifier is optional.
61 © Luxoft Training 2012 Interfaces An interface that is not nested cannot be private. An interface cannot be protected. public interface can be implemented by any class. default interface can be implemented by any class from the package that defines the interface itself.
62 © Luxoft Training 2012 Interfaces It is assumed that all interface methods are declared as public abstract.
63 © Luxoft Training 2012 Interfaces When overriding the method you cant reduce its visibility.
64 © Luxoft Training 2012 Interfaces A behavior can extend another behavior. public interface Set extends Collection, Comparator {... } Note! the class that implements extended interface must implement methods of both interfaces.
65 © Luxoft Training 2012 Complex example
66 © Luxoft Training 2012 Complex example
67 © Luxoft Training 2012 The stack and the heap
68 © Luxoft Training 2012 Constructors It should be ensured that childs constructor will be called after parents constructor. The super(arg1, …) keyword is used to call superclass constructor. The needed constructor is selected by the list of the arguments.
69 © Luxoft Training 2012 Constructors The super(arg1, …) keyword is used to call superclass constructor. class SuperClass { public: SuperClass(int foo) { // do something with foo } }; class SubClass : public SuperClass { public: SubClass(int foo, int bar) : SuperClass(foo) { // do something with bar } }; class SuperClass { public SuperClass(int foo) { // do something with foo } class SubClass extends SuperClass { public SubClass(int foo, int bar) { super(foo); // do something with bar } C++Java
70 © Luxoft Training 2012 Constructors The this reference can be used to call overloaded constructor.
71 © Luxoft Training 2012 Method overloading Only type of an argument is considered, not a parameter name. Therefore, the following method is not considered overloaded:
72 © Luxoft Training 2012 Method overriding Overriding method must: Have the same name and arguments list as parent class method The return type should be the same or its subclass. Requirements to overridden method: final cannot be overridden Access modifier shall not be narrower Overridden method should throw exceptions of the same type or subclass
73 © Luxoft Training 2012 Method overriding example
74 © Luxoft Training 2012 Object killer #1 public class StackRef { public void foof() { barf(); } public void barf() { Duck d = new Duck(); } Reference goes out of scope, permanently.
75 © Luxoft Training 2012 Object killers #2 and #3 Assign the reference to another object public class ReRef { Duck d = new Duck(); public void go() { d = new Duck(); } Explicitly set the reference to null public class ReRef { Duck d = new Duck(); public void go() { d = null; }
76 © Luxoft Training 2012 Static methods Static methods cant use non-static (instance) variables!
77 © Luxoft Training 2012 Static imports
78 © Luxoft Training 2012 Constants static final variables are constants public static final double PI = ;
79 © Luxoft Training 2012 Final modifier
80 © Luxoft Training 2012 Every class is Object
81 © Luxoft Training 2012 Wrapper classes
82 © Luxoft Training 2012 Wrapper classes
83 © Luxoft Training 2012 Autoboxing/unboxing Integer i = 3; public void doNumsNewWay() { List listOfNumbers = new ArrayList (); listOfNumbers.add(3); int num = listOfNumbers.get(0); }
84 © Luxoft Training 2012 Primitive wrappers Java provides wrapper classes for each primitive data types. java.lang. Wrappers are found in the Byte, Short, Integer, Long, Float, Double, Character In new Java versions you may use wrappers absolutely transparently. Integer count = 1; Boolean isReady = false;
85 © Luxoft Training 2012 Primitive wrappers Java automatically converts an object to a primitive type if it is required. The Boolean object will contain true, if the constructor parameter will be equal to true sting in any case. Boolean isReady = new Boolean(TRue); //true Boolean isReady = new Boolean(Yes); //false
86 © Luxoft Training 2012 Primitive wrappers Each class has a set of constants with maximum and minimal values. Integer.MIN_VALUEInteger.MAX_VALUE Each class has static methods for converting type from string. Double.parseDouble(String s) Numeric types are inherited from the Number class.
87 © Luxoft Training 2012 Primitive wrappers The Double class has the method of checking whether the number is infinite. Double.isInfinity(double d) The Integer class has useful methods for work with binary representation of integers. Integer.reverse(int i) Integer.bitCount(int i) Integer.numberOfLeadingZeros(int i)
88 © Luxoft Training 2012 Primitive wrappers To work with bigger numbers, classes from the java.math package can be used: BigInteger and BigDecimal Numbers are stored as strings. BigInteger number = new BigInteger("33"); BigInteger big = number.pow(10000);
89 © Luxoft Training 2012 Enumerations
90 © Luxoft Training 2012 Enumerations Very often we have to introduce enumerated types:
91 © Luxoft Training 2012 Enumerations Java 1.5 introduced new enumeration mechanism (enum). Enumeration is java.lang.Enum classs subclass. Enumeration solves this problem and can be applied to the switch operator. Enumeration is a usual class with some limitations.
92 © Luxoft Training 2012 Difference between enumerations and classes Declared with the help of enum. Enumeration instance cannot be explicitly created. Enumeration cannot be extended. Enumeration can be the switch argument. Has embedded name() method that prints enumeration values.
93 © Luxoft Training 2012 Enumerations
94 © Luxoft Training 2012 Enumerations
95 © Luxoft Training 2012 Working on the Bank Application Exercise