Introduction to Object-Oriented Concepts in Java

Slides:



Advertisements
Similar presentations
Chapter 1: Computer Systems
Advertisements

Programming with Java. Problem Solving The purpose of writing a program is to solve a problem The general steps in problem solving are: –Understand the.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
The Java Programming Language
CMT Programming Software Applications
Outline Java program structure Basic program elements
COMP 14: Intro. to Intro. to Programming May 23, 2000 Nick Vallidis.
Chapter 1 Introduction.
String Escape Sequences
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Java Software Solutions Lewis and Loftus Chapter 2 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Software Concepts -- Introduction.
Prepared by Uzma Hashmi Instructor Information Uzma Hashmi Office: B# 7/ R# address: Group Addresses Post message:
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Java Language and SW Dev’t
System development with Java Lecture 2. Rina Errors A program can have three types of errors: Syntax and semantic errors – called.
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
1 Computer Systems -- Introduction  Chapter 1 focuses on:  the structure of a Java application  basic program elements  preparing and executing a program.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
CSC204 – Programming I Lecture 4 August 28, 2002.
Lecture 2 Object Oriented Programming Basics of Java Language MBY.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
© 2012 Pearson Education, Inc. All rights reserved. 1-1 Why Java? Needed program portability – Program written in a language that would run on various.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
 JAVA Compilation and Interpretation  JAVA Platform Independence  Building First JAVA Program  Escapes Sequences  Display text with printf  Data.
Chapter 2: Java Fundamentals
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Chapter 1: Introduction Java Programming Language How the Java Virtual Machine Works (compiling, etc…) Update by: Dan Fleck Coming up: The Java Programming.
Java The Java programming language was created by Sun Microsystems, Inc. It was introduced in 1995 and it's popularity has grown quickly since A programming.
Introduction to Java Java Translation Program Structure
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
© 2004 Pearson Addison-Wesley. All rights reserved ComS 207: Programming I Instructor: Alexander Stoytchev
Lecture 2 Software Concepts Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Introduction to Java Programming by Laurie Murphy Revised 09/08/2016.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
1 Problem Solving  The purpose of writing a program is to solve a problem  The general steps in problem solving are: Understand the problem Dissect the.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
JAVA MULTIPLE CHOICE QUESTION.
Working with Java.
Chapter No. : 1 Introduction to Java.
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Lecture 2: Data Types, Variables, Operators, and Expressions
CSE 190D, Winter 2013 Building Java Programs Chapter 1
Variables and Primative Types
University of Central Florida COP 3330 Object Oriented Programming
Chapter 3 Assignment Statement
Unit 41 – Programing in Java
Starting JavaProgramming
null, true, and false are also reserved.
Introduction to Java Programming
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
An overview of Java, Data types and variables
Chapter 1: Computer Systems
Units with – James tedder
Units with – James tedder
Focus of the Course Object-Oriented Software Development
Introduction to Object-Oriented Concepts in Java
Chap 2. Identifiers, Keywords, and Types
C Language B. DHIVYA 17PCA140 II MCA.
Instructor: Alexander Stoytchev
Zorah Fung University of Washington, Winter 2016
Presentation transcript:

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

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

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

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

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.

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

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.

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

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.

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

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.

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

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

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

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

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

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

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

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

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 = 0.0725; double salesTaxRate = 0.0725; Java programs should be self-documenting.

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

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 -

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

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;

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"

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 ‘$’

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

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

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

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.

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

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

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

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

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

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.

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

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

Selection Statements if statements

Loop Statements if statements

The break & continue Statements if statements

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

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

How Java Works See https://javarevisited.blogspot.com/2014/06/is-java- interpreted-or-compiled-programming-language.html https://www.quora.com/Is-Java-a-compiled-language-or- interpreted-What-is-the-difference-What-is-the-JIT-compiler