Presentation is loading. Please wait.

Presentation is loading. Please wait.

COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva.

Similar presentations


Presentation on theme: "COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva."— Presentation transcript:

1 COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva

2 Course Text Book: Y. Daniel Liang, Introduction to Java Programming, Comprehensive Version, 9th edition, Pearson, 2013

3 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/http://www.codeguru.com/java/tij/ Other useful links (comparisson between C++ and Java): –http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html

4 Eclipse Downloads: –http://www.eclipse.org/downloads/ Tutorials: –http://www.vogella.de/articles/Eclipse/article.html –http://eclipsetutorial.sourceforge.net/totalbeginner.html

5 Overview From the very beginning, Java was designed as an object- oriented 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

6 Versions of Java Java 1 Java 2 Java 5.0 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 1.4: More additions and the assert statement Java 1.5: Generics, enum s, new for loop, and other new syntax Java: Original, not very good version (but it had applets) Java 6 (=1.6): A few new features, mostly at the advanced level

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

8

9 Executing a Java program

10 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.

11 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 (client- side). - You can only run an applet from an HTML page.

12 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.

13 JVM emulation run on a physical machine

14 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.

15 JVM handles translations

16 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

17 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.

18 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) {... }

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

20 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”;

21 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

22

23

24

25

26

27

28

29 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)

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

31

32 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)

33 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.

34 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.

35 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 );

36 // 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

37 public class HelloWorldApp { public static void main(String[] args) { // Display "Hello World!" System.out.println("Hello World!"); } } Example

38 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

39 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 + "!"); } Example

40 import java.util.*; public class test11 { public static void main(String[] args) { System.out.println("Hello, it’s: "); System.out.println(new Date()); }

41 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];

42 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

43 Flow of control if, if-else, if-else if switch for, while, do-while break continue

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

45 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."); }

46 For-loop For (int i=1, j=10; i < j; i++, j-=2) System.out.println("i="+i+" j="+j); for (int i = 0; i < 4; i++){ for( char letter = 'A'; letter <= 'A' + i; letter++) System.out.print(letter); System.out.println(); } i=1 j=10 i=2 j=8 i=3 j=6 A AB ABC ABCD

47 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

48 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


Download ppt "COS 240 Object-Oriented Languages The Anatomy of a Java Program AUBG, Spring 2014 Svetla Boytcheva."

Similar presentations


Ads by Google