Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva Course Text Book: Y. Daniel Liang, Introduction to Java Programming, Comprehensive Version, 9th edition, Pearson, 2013 Aditional Book: Thinking in Java • Bruce Eckel, Thinking in Java (4th Edition) – http://www.planetpdf.com/developer/article.asp?ContentID=6632 – http://www.codeguru.com/java/tij/ • Other useful links (comparisson between C++ and Java): – http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html Eclipse • Downloads: – http://www.eclipse.org/downloads/ • Tutorials: – http://www.vogella.de/articles/Eclipse/article.html – http://eclipsetutorial.sourceforge.net/totalbeginner.html Overview From the very beginning, Java was designed as an objectoriented language - unlike C++ which is just an object-oriented extension to C. But like C#. Classes are the building blocks of Java programs - again, unlike C++. But like C#. Java is case sensitive. Like C#. - a is different to A Versions of Java Java: Original, not very good version (but it had applets) Java 1 Java 1.1: Adds inner classes and a completely new event-handling model Java 1.2: Includes “Swing” but no new syntax Java 1.3: Additional methods and packages, but no new syntax Java 2 Java 1.4: More additions and the assert statement Java 1.5: Generics, enums, new for loop, and other new syntax Java 5.0 Java 6 (=1.6): A few new features, mostly at the advanced level How Java Works • Java's platform independence is achieved by the use of the Java Virtual Machine (JVM). • A Java program consists of one or more files with a .java extension • these are just text (i.e. source) files. • When a Java program is compiled, the .java files are fed to the compiler which produces a .class file for each .java file. • The .class file contains Java bytecode. • • Java bytecode is like machine language, but it is intended for the Java Virtual Machine, not a specific processor. Executing a Java program • To run a Java program, the bytecode in a .class file is fed to an interpreter/compiler which converts the bytecode to machine code for a specific processor. • Some people refer to the interpreter/compiler as "The Java Virtual Machine" (JVM). • The interpreter/compiler is platform specific because it takes the platform-independent bytecode and produces machine language instructions for a particular processor. • So a Java program could be run an any type of computer that has a JVM written for it. Java was initially developed by Sun Microsystems - producers of Unix platforms and Unix OS. Java programs may be applications or applets. Applications are standalone programs, similar to .NET Console and Windows applications. Applets are similar to applications, but they do not run as standalone programs. - Instead, applets adhere to a set of conventions that lets them run within a Java-compatible browser (clientside). - You can only run an applet from an HTML page. JVM is an Emulation • The difficult part of creating Java byte code is that the source code is compiled for a machine that does not exist. • This machine is called the Java Virtual Machine, and it exists only in the memory of our computer. • Fooling the Java compiler into creating byte code for a nonexistent machine is only one-half of the ingenious process that makes the Java architecture neutral. • The Java interpreter must also make our computer and the byte code file believe they are running on a real machine. It does this by acting as the intermediary between the Virtual Machine and our real machine. JVM emulation run on a physical machine JVM • The Java Virtual Machine is responsible for interpreting Java byte code and translating this into actions or Operating System calls. • For example, a request to establish a socket connection to a remote machine will involve an Operating System call. • Different Operating Systems handle sockets in different ways - but the programmer doesn't need to worry about such details. It is the responsibility of the JVM to handle these translations so that the Operating System and the CPU architecture on which the Java software is running is completely irrelevant to the developer. JVM handles translations Preview to Java Language • Basic syntax the same as C++ (which was then copied by C#!). • Pointers exist but in a simplified and hidden form. – Object references • Garbage Collection is used – No need for destructors (but may have!). – Memory leaks very unlikely . – Not as many memory management issues (Memory is still managed, but by the run time system instead of the programmer.). • Array index out of bounds causes a runtime error – Java uses the term Exceptions for runtime errors Basic syntax for class declaration In Java, a class comprises a class header and class body. public class class_name { class body; } Note: No semicolon (;) to terminate class block. But statements must be terminated with a ; Class body comprises class members – constructor, data fields and methods. Each feature (constructor, data fields and methods) is individually tagged as public or private. (There are other qualifiers …) E.g. public class class_name { private data_type name; public method_name(parameters) { ... } public another_method(parameters) { ... } } Reference Types • Non-primitive types in Java are called reference types. • Variable does not really hold an object, it holds a reference to (i.e. address of) the object. • Java hides this indirection from you. Like C#. In Java, declaring a variable to hold an object does not create the object (instance) itself. Need to invoke constructor (via new) to create and initialize instance. The variable only holds a reference to the object. class_name variable_name; To create an instance of a class, use the new operator which invokes the class constructor. new class_name(parameters) Variables of type class_name can be created in this way: class_name instance_name = new class_name(params); An object of type String can be created by simply enclosing the characters in double quotes String s = “Here is a string”; The dot operator . is used in conjunction with the object to access the members of a class (like C++ and C#). Every class defined in Java must extend some other object – Default: implicit extension of the Object class Syntax for simple Java program public class class_name { public static void main(String[] args) { implementation of method } } The first method that will be invoked when execution commences must be called main(). Note the case of main() and String ! - C# has public static void Main(string[] args) // Java public class Hello { public static void main(String[] args) { System.out.println("Hello world in Java"); } } // C# public class Hello { public static void Main(string[] args) { System.Console.WriteLine("Hello world in C#"); System.Console.ReadLine(); } } The general syntax for a method modifers return_type method_name(parameters) { data declarations sequence of statements } E.g. public static void main(String[] args) Import statement A Java program is never entirely self-contained but instead must execute in the “world” provided by the Java runtime system. Use of the import statement: import java.lang.*; This statement makes the methods in the library package java.lang available to the class following it. java.lang is just one package in the Java library or API. Actually, importing java.lang is not required since it is automatically available to all Java programs. The package java.lang is important because it contains the class System which itself contains I/O methods. E.g. Methods System.out.print(...)and System.out.println(...)and System.in.read() A Java package is similar to a C# namespace. Standard Output • To print to standard output use System.out.print( expression ); // no newline System.out.println( expression ); // newline System.out.println( ); // just a newline Common behaviour is to build up expression to be printed out System.out.println( "x is: " + x + " y is: " + y ); Example // Package Declaration import java.lang.*; // not required // Program start class public class HelloWorld { // Main begins program execution public static void main(string[] args) { // This is a single line comment /* This is a multiple line comment */ System.out.println("Hello World!"); } } Example public class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); } } Example import java.io.*; public class Testclass { public static void main( String args[] ) { int count = 0; while ( count < 10 ) { System.out.println("counter is " + count ); count++; } } } Example public class HelloWorld { public static void main(String[] args) { String name = "Java"; // See if an argument was passed from the command line if (args.length == 1) name = args[0]; System.out.println("Hello, " + name + "!"); } } import java.util.*; public class test11 { public static void main(String[] args) { System.out.println("Hello, it’s: "); System.out.println(new Date()); } } Language Basics • Data types – 8 primitive types: • boolean, byte, short, int, long, float, double, char – Class types, either provided by Java, or made by programmers (Reference types) • String, Object, Frame, Person, Animal, … – Array types (also reference types) • Variables – dataType identifier [ = Expression]: – Example variable declarations and initializations: int x; x=5; boolean b = true; Frame win = new Frame(); String x = “How are you?”; int[] intArray; intArray = new int[2]; intArray[0] = 12; intArray[1] = 6; Person pArray = new Person[10]; Constants via final Assigned value cannot be changed – Similar to the const keyword in C Variables declared with final – must be initialized in the declaration – can be initialized in a constructor, but must be assigned a value in every constructor of the class Flow of control if, if-else, if-else if switch for, while, do-while break continue If-else /** * return the difference of x and y */ public static int abs(int x, int y){ if (x < y) return y - x; else if(x > y) return x - y; else return 0; } Switch-case switch ( N ) { // (Assume N is an integer variable.) case 1: System.out.println("The number is 1."); break; case 2: case 4: case 8: System.out.println("The number is 2, 4, or 8."); System.out.println("(That's a power of 2!)"); break; case 3: case 6: case 9: System.out.println("The number is 3, 6, or 9."); System.out.println("(That's a multiple of 3!)"); break; case 5: System.out.println("The number is 5."); break; default: System.out.println("The number is 7 or is outside the range 1 to 9."); } For-loop For (int i=1, j=10; i < j; i++, j-=2) System.out.println("i="+i+" j="+j); i=1 j=10 i=2 j=8 i=3 j=6 for (int i = 0; i < 4; i++){ for( char letter = 'A'; letter <= 'A' + i; letter++) System.out.print(letter); System.out.println(); } A AB ABC ABCD The break statement • Inside any loop, the break statement will immediately get you out of the loop – If you are in nested loops, break gets you out of the innermost loop • It doesn’t make any sense to break out of a loop unconditionally - you should do it only as the result of an if test Example: for (int i = 1; i <= 12; i++) { if (badEgg(i)) break; } • break is not the normal way to leave a loop – Use it when necessary, but don’t overuse it The continue statement • Inside any loop, the continue statement will start the next pass through the loop – In a while or do-while loop, the continue statement will bring you to the test – In a for loop, the continue statement will bring you to the increment, then to the test