Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Object-Oriented Concepts in Java

Similar presentations


Presentation on theme: "Introduction to Object-Oriented Concepts in Java"— Presentation transcript:

1 Introduction to Object-Oriented Concepts in Java
Overview of Java Introduction to Object-Oriented Concepts in Java

2 Outline How Java works The JVM Java Program Structure
Overview of classes

3 How Java Works e.g. Bank.java javac e.g. Bank.class by JIT compiler

4 The Compiler and the Java Virtual Machine
Most compilers translate source code into executable files containing machine code. The Java compiler translates a Java source file into a .class file that contains byte code instructions. Byte code instructions are the machine language of the Java Virtual Machine (JVM) and cannot be directly executed by the CPU. 3) JVM interprets and executes these class files on the target platform. Uses JIT (Just In Time) translator to compile parts of bytecode into native code. This native code is directly executed by platform

5 The Compiler and the Java Virtual Machine
Byte code files end with the .class file extension. The JVM is a program that emulates a micro- processor. The JVM executes instructions as they are read. JVM is often called an interpreter. Java is often referred to as an interpreted language.

6 Java Basics The Java compiler (javac) is a command line utility.
The command to compile a program is: Javac filename.java E.g. Javac Payroll.java The .java file extension is required. The command to execute a program is: Java filename Where filename.class file was produced by javac

7 The JVM and Portability
With most programming languages, portability is achieved by compiling a program for each CPU it will run on. Java provides an JVM for each platform so that programmers do not have to recompile for different platforms.

8 The JVM and Portability
Byte code (.class) Java Virtual Machine for Windows Java Virtual Machine for Unix Java Virtual Machine for Linux Java Virtual Machine for Macintosh

9 Java Applications and Applets
Java programs can be of two types: Applications Stand-alone programs that run without the aid of a web browser. Relaxed security model since the user runs the program locally. Applets Small applications that require the use of a Java enabled web browser to run. Enhanced security model since the user merely goes to a web page and the applet runs itself.

10 Java Program Structure
Package statement import statement Class declaration 1 Class declaration 2 public class declaration public static void main(String[] args) Class declaration n

11 The Java Virtual Machine & main()
The main method is the first method that is executed when a class is loaded into memory and executed by the JVM. If another class loaded has a main method, the second main method will be ignored.

12 Class with one method //This is my first Java program
Comment //This is my first Java program public class HelloWorld { } Class header public static void main (String[] args) { System.out.println(“Hello World!”); } The main method Class body public static void main (String[] args) { } // comments about the method method header method body 12

13 Syntax of Class Definition
[ClassModifiers] class ClassName [extends SuperClass] [implements Interface1, Interface2, …] { ClassMemberDeclarations } ClassModifiers = public/abstract/final ClassModifiers is never private except for inner classes. 13

14 A Java Program may contain
A Simple Java Program Name of class Reserved word Class accessibility Main program Note the syntax for the method header Class HelloWorld A Java Program may contain many classes public class HelloWorld { public static void main (String[] args) System.out.println(“Hello World!”); } Class Bank Account Class BillPayment Notation for using methods: class.method or package.class.method is how to refer to a public method (with some exceptions). The HelloWorld Class Class OnlineShopping 14

15 Class with many methods
public class Account { String clientName; char accType = `S’; int accNumber; double balance=0; public static void deposit(double value){ if(value > 0) balance = balance + value; } //end of method public static void withdraw(double value){ if(balance > value) balance = balance - value }//end of method public static double getBalance(){ return balance; public static String getName(){ return clientName; public static void setName(String theName){ clientName = theName; }//end of method public static int getAccNumber(){ return accNumber; public static void setAccNumber(int n){ accNumber = n; }//end of class public static void main (String[] args){ Account acc = new Account(); acc.deposit(200); acc.deposit(400.95); acc.withdraw (100); } 15

16 Identifiers Identifiers are programmer- defined names for: Classes
TestPrint Variables number, age, myState Methods main, print, locateVehicle public class TestPrint { public static void main(String[] args) { int myState = “North Carolina”; System.out.print("I live in “ + myState); }

17 Identifiers: Programmer Defined Names
Java programs are written in Unicode Identifiers must follow certain rules: An identifier may only contain: Characters in the alphabets of all languages in Unicode letters a–z or A–Z the digits 0–9, underscores (_), or the dollar sign ($) The first character may not be a digit. Java is case sensitive. Total, total, and TOTAL are different identifiers Identifiers cannot include spaces. A reserved word cannot be used as an identifier

18 Java Reserved Keywords
abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while Reserved Words have a predefined meaning in the Java language, e.g., if, while. A reserved word cannot be used in any other way

19 Java Naming Conventions
By convention, programmers use different case styles for different types of identifiers, such as title case for class names - Lincoln upper case for constants – MAXIMUM lower case followed by title case for method names – myHomeState A general rule of thumb about naming variables and classes are that, with some exceptions, their names tend to be nouns or noun phrases. 19

20 Other Rules for Creating Names
Variable names should be descriptive. Descriptive names allow the code to be more readable; therefore, the code is more maintainable. Which of the following is more descriptive? double tr = ; double salesTaxRate = ; Java programs should be self-documenting.

21 Data Types in Java A data type denotes a set of a certain collection of data. For example, numbers as against strings. Java supports two broad categories of data types. Primitive types Reference types

22 Primitive Data Types Primitive data types are built into the Java language and are not derived from classes. There are 8 Java primitive data types. Data Type Name/Java Keyword Size Min Value Max Value Integer / Whole Number byte 1 byte – 8 bits -27 27 -1 short 2 bytes – 16 bits -215 215 -1 int 4 bytes – 32 bits -231 231 -1 long 8 bytes – 64 bits -263 263 -1 Real /floating Point Number float ~ -2126 ~ 2127 double ~ 21022 ~ 21023 Character char Can represent any Unicode character True/False boolean -

23 Reference Types There are three forms of reference types Class type
public class ClassName{ //code for class } Interface type public interface InterfaceName{ //method signatures Array type int[] numbers;//array declaration numbers = new int[20]; //allocate memory for the array

24 Variable Declaration modifier = public, private, protected
[modifier] Type variableName1 [=InitialValue1] [, variableName2 [=InitialValue2]] [, variableName3 [=InitialValue3]] … ; modifier = public, private, protected protected int total; public IAccount intf1, intf2; public Account acc1, acc2; private double average = 100, sum =44.88; public char ch1, ch2=‘3’, ch3; private boolean itemFound;

25 Numeric & String Literals
Literals are actual values. Numeric literals 124 44.76 String literals "To be or not to be" "Love is lovely" "1" "X"

26 Character Literals Character literals
ASCII characters can be written directly in single quotes. '1' 'X‘ In hexadecimal code \u is followed by four hexadecimal digits '\u0040‘ – the character In octal code \ is followed by three octal digits '\044' – the character ‘$’

27 String Escape Sequences
What if we wanted to print a double quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you.");

28 Java Escape Sequence Escape Sequence \b \t \n \r \" \' \\ Meaning
backspace tab newline carriage return double quote single quote backslash

29 Local, Global and Class Variables A variable is a location in memory where a value can be stored and changed. Global/ Instance variable Declared in the class Local variable Declared within the body of a method. Class variable Global variable declared as static

30 Primitive vs Reference Variables
References 32 bit pointers Hold addresses not data values Memory allocated from garbage-collected heap No need to de-allocate memory. Equality of references? Garbage Collection Unused/unreacheable memory (garbage) automatically dealocated. Comes at a cost to performance.

31 One Dimensional Arrays
Declaration int[] array; Creation Using the new operator Size of array must be specified All elements are initialized to default values Integers 0, floating point 0.0, char \u000, Boolean false, Reference null E.g. int numbers = new int[20]; Using the one-dimensional array initializer {e0, e1, e2, …, en-1} E.g. int[] numbers = {1,2,3,4,5,6,7};

32 One Dimensional Arrays
Indexing Using for loop Slicing Using Arrays.copyOfRange(array, start, stopPlusOne)

33 Multi-Dimensional Arrays
Is treated as an array of arrays A one dimensional array where each element is an array. Declaration String[][] names; // 2 dimensions double[][][] values;//3 dimensions Creation Using the new operator arrayName = new Type[n1] [n1] [n2] … [nk] // k dimensions All elements are initialized to default values E.g. int[][] numbers = new int[10][20; Using the one-dimensional array initializer {e0, e1, e2, …, en-1} E.g. int[][] numbers = {1,2,3,4,5,6,7}; Indexing

34 Arithmetic Operators General Assignment operators Increment/Decrement
+ addition - subtraction * Multiplication / division % remainder/modulus Assignment operators +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |= Increment/Decrement ++, --

35 Bitwise Operators ~x x & y x | y x ^ y Complement of x
bitwise and of x and y x | y bitwise inclusive or of x and y x ^ y bitwise exclusive or of x and y

36 Shift Operators x << k = x*2k x >> k = x/2k
Shifts the bits in x k places to the left x >> k = x/2k Shifts the bits in x, k places to the right, filling in with the highest bit (the sign bit) on the left-hand side. x >>> k Shifts the bits in x k places to the right, filling in with 0 bits on the left-hand side.

37 Logical Operators Translating logic into Java AND && OR || XOR ^ NOT !

38 Relational Operators == != < > <= >=

39 Selection Statements if statements

40 Loop Statements if statements

41 The break & continue Statements
if statements

42 The End Qu es ti ons? ______________________ Devon M. Simmonds
Computer Science Department University of North Carolina Wilmington _____________________________________________________________

43 Example of a Java Class public class Account implements IAccount {
private String accName; private int accNumber; private double balance; public boolean deposit(double amount){ if(amount > 0){ this.balance += amount; return true; } return false; public boolean withdraw(double amount){ if(this.balance >= amount){ this.balance -= amount; }//end of class Example of a Java Class

44 How Java Works See interpreted-or-compiled-programming-language.html interpreted-What-is-the-difference-What-is-the-JIT-compiler


Download ppt "Introduction to Object-Oriented Concepts in Java"

Similar presentations


Ads by Google