Java Overview An introduction to the Java Programming Language

Similar documents
Java Control Statements

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Java Classes. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Language Basics: Introduction To Java, Basic Features, Java Virtual Machine Concepts, Primitive Data Type And Variables, Java Operators,

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Introduction to Programming Using Java (98-388)

Index COPYRIGHTED MATERIAL

Tools : The Java Compiler. The Java Interpreter. The Java Debugger

Inheritance in Java. Produced by: Eamonn de Leastar Dr. Siobhán Drohan

Pace University. Fundamental Concepts of CS121 1

1 Shyam sir JAVA Notes

Chapter 2: Using Data

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

An overview of Java, Data types and variables

Operators and Expressions

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Programming. Syntax and Semantics

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Full file at

Language Fundamentals Summary

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

Java Primer 1: Types, Classes and Operators

3. Java - Language Constructs I

Points To Remember for SCJP

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Operators. Java operators are classified into three categories:

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Java language. Part 1. Java fundamentals. Yevhen Berkunskyi, NUoS

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

A Quick Tour p. 1 Getting Started p. 1 Variables p. 3 Comments in Code p. 6 Named Constants p. 6 Unicode Characters p. 8 Flow of Control p.

B.V. Patel Institute of BMC & IT, UTU 2014

A variable is a name for a location in memory A variable must be declared

JAVA Programming Fundamentals

Full file at

Special Topics: Programming Languages

CS 231 Data Structures and Algorithms, Fall 2016

2 rd class Department of Programming. OOP with Java Programming

1/16/2013. Program Structure. Language Basics. Selection/Iteration Statements. Useful Java Classes. Text/File Input and Output.

An Introduction to Processing

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

Visual C# Instructor s Manual Table of Contents

CSC Java Programming, Fall Java Data Types and Control Constructs

Key Differences Between Python and Java

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

WA1278 Introduction to Java Using Eclipse

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

CSC 1214: Object-Oriented Programming

CS313D: ADVANCED PROGRAMMING LANGUAGE

Decaf Language Reference Manual

CS112 Lecture: Primitive Types, Operators, Strings

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

Core JAVA Training Syllabus FEE: RS. 8000/-

CSE P 501 Compilers. Java Implementation JVMs, JITs &c Hal Perkins Winter /11/ Hal Perkins & UW CSE V-1

NOOTAN PADIA ASSIST. PROF. MEFGI, RAJKOT.

Java Basic Datatypees

CS11 Java. Fall Lecture 1

Sir Muhammad Naveed. Arslan Ahmed Shaad ( ) Muhammad Bilal ( )

15CS45 : OBJECT ORIENTED CONCEPTS

Chapter 2: Using Data

Java: framework overview and in-the-small features

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Introduction to. Android Saturday. Yanqiao ZHU Google Camp School of Software Engineering, Tongji University. In courtesy of The Java Tutorials

Client-Side Web Technologies. JavaScript Part I

Computer Programming : C++

Chapter 02: Using Data

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

FRAC: Language Reference Manual

The Arithmetic Operators. Unary Operators. Relational Operators. Examples of use of ++ and

The Arithmetic Operators

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

The Warhol Language Reference Manual

Java+- Language Reference Manual

CS260 Intro to Java & Android 03.Java Language Basics

Zheng-Liang Lu Java Programming 45 / 79

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

5/23/2015. Core Java Syllabus. VikRam ShaRma

Compaq Interview Questions And Answers

Unit 2: Java in the small

Computer Components. Software{ User Programs. Operating System. Hardware

Java Programming. Atul Prakash

Chapter 2: Data and Expressions

UNIT- 3 Introduction to C++

Java Programming Training for Experienced Programmers (5 Days)

Chapter 1 INTRODUCTION SYS-ED/ COMPUTER EDUCATION TECHNIQUES, INC.

Core Java Contents. Duration: 25 Hours (1 Month)

Program Fundamentals

Modern Programming Languages. Lecture Java Programming Language. An Introduction

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java Training JAVA. Introduction of Java

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Java Programming with Eclipse

Transcription:

Java Overview An introduction to the Java Programming Language Produced by: Eamonn de Leastar (edeleastar@wit.ie) Dr. Siobhan Drohan (sdrohan@wit.ie) Department of Computing and Mathematics http://www.wit.ie/

2

Essential Java Overview Introduction Syntax Basics Arrays Classes Classes Structure Static Members Commonly used Classes Control Statements Control Statement Types If, else, switch For, while, do-while Inheritance Class hierarchies Method lookup in Java Use of this and super Constructors and inheritance Abstract classes and methods Interfaces Collections ArrayList HashMap Iterator Vector Enumeration Hashtable Exceptions Exception types Exception Hierarchy Catching exceptions Throwing exceptions Defining exceptions Common exceptions and errors Streams Stream types Character streams Byte streams Filter streams Object Serialization 3

Overview: Road Map Java Introduction History Portability Compiler Java Virtual Machine Garbage collection Java Syntax Identifiers Expressions Comments Java Basics Java types Primitives Objects Variables Operators Identity and equality Arrays What are arrays? Creating arrays Using arrays 2

Java History Originally was called Oak. Was intended to be used in consumer electronics Platform independence was one of the requirements Based on C++, with influences from other OO languages (Smalltalk, Eiffel ) Started gaining popularity in 1995 Renamed to Java. Was good fit for the Internet applications. 4

Portability Java is platform independent language Java code can run on any platform. Promotes the idea of writing the code on one platform and running it on any other. Java also supports native methods Native methods are written in another language e.g. C, C++. Native methods are platform specific don t run on the JVM. Breaks the idea of platform independence. Typically used to access/control hardware, interface to system calls or libraries written in other languages, or to improve efficiency in certain tasks. 5

Compiler Bytecode: Can run on any platform with a JVM platform independent. Byte code is the same, regardless of platform. Is not a machine code. Must be interpreted in the machine code at runtime. 6

Java Virtual Machine (JVM) JVM is different for different platforms. JVM processes bytecode at runtime by translating bytecode into machine code (i.e. interprets it!). 7

Memory Management Automatic Garbage Collection is built into Java: occurs whenever memory is required can be forced programmatically 8

Distributed Systems (low level) When you write Java programs that communicate over the network, you are programming at the application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you can use the classes in the java.net package. You just need to decide on the protocol. More Info: http://docs.oracle.com/javase/tutorial/networking/overview/networking.html 9

Distributed Systems (high level) Remote Method Invocation (RMI) is Java s distributed protocol, providing for remote communication between programs written in Java. Allows an object running in one JVM to invoke methods on an object running in another JVM. Use java.rmi package. More Info: https://docs.oracle.com/javase/tutorial/rmi/ 9

Concurrency Java includes support for multithreaded applications API for thread management is part of the language (java.util.concurrent) A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. Source: http://www.tutorialspoint.com/java/java_multithreading.htm 10

Overview: Road Map Java Introduction History Portability Compiler Java Virtual Machine Garbage collection Java Syntax Identifiers Expressions Comments Java Basics Java types Primitives Objects Variables Operators Identity and equality Arrays What are arrays? Creating arrays Using arrays 2

Identifiers Used for naming classes, interfaces, methods, variables, fields, parameters. Are case-sensitive. Begin with either: a letter (preferable), the dollar sign "$", or the underscore character "_". Can contain letters, digits, dollar signs, or underscore characters. Can be any length you choose. Must not be a keyword or reserved word e.g. int, while, etc. Cannot contain white spaces. 12

Messages and Objects Objects send messages to other objects contact.setname( Mike ); separator statement ending message receiver message argument 13

Expressions Statements are the basic Java expressions Semicolon (;) indicates end of a statement variable declaration variable assignment object creation HomePolicy homepolicy; double premium; premium = 100.00; homepolicy = new HomePolicy(); homepolicy.setannualpremium(premium); message sending 14

Empty Expression Semicolon on its own in the line Can be used to indicate do nothing scenario in the code ; //this is an empty statement for(int i=1; i<3; i++) ; System.out.println(i); We would expect the code to print 1,2 but it prints only 1 because of the empty statement 15

Comments 3 different types of comments in Java: Single line comment Starts with // and ends at the end of the line Multiple line comment Starts with /* and ends with */ Javadoc comment: starts with /** and ends with */ used by Javadoc program for generating Java documentation /** Javadoc example comment. * Used for generation of the documentation. */ /* Multiple line comment. * */ // Single line comment. 16

Literals Represent hardcoded values that do not change Typical example are string literals When used compiler creates an instance of String class String one = "One"; String two = "Two"; String one = new String("One"); String two = new String("Two"); 17

Overview: Road Map Java Introduction History Portability Compiler Java Virtual Machine Garbage collection Java Syntax Identifiers Expressions Comments Java Basics Java types Primitives Objects Variables Operators Identity and equality Arrays What are arrays? Creating arrays Using arrays 2

Java and Types There are two different types in Java: Primitive data type (e.g. premium). Reference type (e.g. homepolicy). Java is strongly typed language Fields, variables, method parameters and returns must have a type. variable name variable type double premium; HomePolicy homepolicy; 19

Primitives Primitives represent simple data in Java. Primitives are not objects in Java Messages cannot be sent to primitives. Messages can be sent to Wrapper classes that represent primitives (found in java.lang package). 20

Primitive Types Keyword Size Min value Max value boolean true/false byte 8-bit -128 127 short 16-bit -32768 32767 char 16-bit Unicode int 32-bit -2147483648 2147483647 float double 32-bit 64-bit long 64-bit - 9223372036854775808 9223372036854775807 21

Primitives Operators Keyword Description Keyword Description Keyword Description + add < lesser & and - subtract > greater or * multiple = assignment ^ xor / divide >= greater equal! not % reminder <= less equal && lazy and the code within is ( ) executed first == equals lazy or ++op increment first!= not equal << left bit shift --op decrement first x+=2 x=x+2 >> right bit shift op++ increment after x-=2 x=x-2 >>> right bit shift with zeros op-- decrement after x*=2 x=x*2 22

boolean Type Commonly used in control statements. Consists of two boolean literals: true false!true //false true & true //true true false //true Keyword Description! complement & and or ^ exclusive or false ^ true //true true ^ false //true false ^ false //false true ^ true //false XOR: outputs true only when inputs differ (one is true, the other is false) && lazy and lazy or false && true //false, second operand does not evaluate true false //true, second operand does not evaluate 23

char Type Represents characters in Java. Uses 16-bit Unicode for support of internationalization. Character literals appear in single quotes, and include: Typed characters, e.g. 'z' Unicode, e.g. '\u0040', equal to '@' Escape sequence, e.g. '\n' 24

Escape Sequence Characters Commonly used with print statements: Escape sequence Unicode Description \n \u000a New line \t \u0009 Tab \b \u0008 Backspace \r \u000d Return \f \u000c Form feed \\ \u005c Backslash \ \u0027 Single quote \ \u0022 Double quote 25

Numeric Types 26

Manipulating Numeric Types A lesser type is promoted to greater type and than operation is performed 12 + 24.56 //int + double = double A greater type cannot be promoted to lesser type Assigning double value to int type variable would result in compile error int i = 12; double d = 23.4; i = d; Type mismatch 27

Manipulating Numeric Types Hashed arrow: some of the least significant digits may be lost by the conversion. 28

Type Casting Values of greater precision cannot be assigned to variables declared as of lower precision types. Type casting makes primitives to change their type Used to assign values of greater precision to variables declared as lower precision e.g. it s possible to type cast double to int type int i = 34.5; //compiler error - type mismatch int i = (int)34.5; //explicit type casting 28

Reference Types Reference types in Java are class or interface also known as object types. If a variable is declared as a type of class An instance of that class can be assigned to it. An instance of any subclass of that class can be assigned to it. If a variable is declared as a type of interface An instance of any class that implements the interface can be assigned to it. 29

Reference Type Reference type names are uniquely identified by: Name of the package where type is defined (class or interface) Type name java.lang.object pim.contact Package name Type name 30

Object Operators Keyword Description instanceof object type!= not identical == identical = assignment 31

Creating Objects in Java Objects are, in Java, created by using constructors. Constructors are methods that have same name as the class: They may accept arguments mainly used for fields initialization If constructor is not defined, the default constructor is used. HomePolicy firstpolicy = new HomePolicy(); HomePolicy secondpolicy = new HomePolicy(1200); 32

Assignment Assigning an object to a variable binds the variable to the object HomePolicy firstpolicy = new HomePolicy(1100); HomePolicy secondpolicy = new HomePolicy(1200); HomePolicy 1100 HomePolicy 1200 firstpolicy = secondpolicy; HomePolicy 1100 HomePolicy 1200 33

Identical Objects Operand == is used for checking if two objects are identical Objects are identical if they occupy same memory space int x = 3; int y = 3; x == y; //true 3 HomePolicy firstpolicy = new HomePolicy(1200); HomePolicy secondpolicy = new HomePolicy(1200); HomePolicy 1200 HomePolicy 1200 firstpolicy == secondpolicy; //false 34

Identical Objects Variables that reference objects are compared by value Objects are identical if their memory addresses are the same Variables are identical if they refer to exactly same instance of the class HomePolicy firstpolicy = new HomePolicy(1200); HomePolicy secondpolicy = firstpolicy; firstpolicy == secondpolicy; //true HomePolicy 1200 35

Equal Objects Determined by implementation of the equals() method. Default implementation is in the Object class (uses identity ==). Usually overridden in subclasses to provide criteria for equality. HomePolicy firstpolicy = new HomePolicy(1200,1); HomePolicy secondpolicy = new HomePolicy(1200,1); firstpolicy.equals(secondpolicy); 36

null Used to un-assign an object from a variable Object is automatically garbage collected if it does not have a reference. When a variable of object type is declared it is assigned null as a value. String one = "One"; one = null; one = "1"; HomePolicy policy; policy = new HomePolicy(1200); ( null if (policy!= { System.out.println(policy.toString()); } 37

Overview: Road Map Java Introduction History Portability Compiler Java Virtual Machine Garbage collection Java Syntax Identifiers Expressions Comments Java Basics Java types Primitives Objects Variables Operators Identity and equality Arrays What are arrays? Creating arrays Using arrays 2

What is an Array? Arrays are basic collections in Java They contain elements of the same type Elements can either be Java objects or primitives Arrays are fixed-size sequential collection Size is predefined, and arrays cannot grow Arrays are objects 39

Array Basics Arrays are automatically bounds-checked When accessing elements that are out of bounds, an exception will be thrown e.g. accessing element at index 10 in the above example will throw the exception. 40

Creating Arrays Arrays store objects of specific type One array cannot store objects of different types, String and int for example. To define a variable that holds an array, you suffix the type with square brackets [] This indicates that variable references an array int[] arrayofintegers; String[] arrayofstrings; or int arrayofintegers[]; String arrayofstrings[]; 41

Creating Arrays There are two ways to create an array: Explicitly using the keyword new Using array initializer When creating an array explicitly its size must be specified: This indicates desired number of elements in the array Elements in the array are initialized to default values int arrayofintegers[]; arrayofintegers = new int[5]; 43

Array Initializer Used for creating and initializing arrays Array elements are initialized within the curly brackets int[] arrayofintegers = {1,2,3,4,5}; Can only be used when declaring variable Using array initializer in a separate step will result in a compilation error int[] arrayofintegers; arrayofintegers = {1,2,3,4,5}; 44

Initializing Arrays If not using initializer, an array can be initialized by storing elements at proper index int[] arrayofintegers; arrayofintegers = new int[5]; arrayofintegers[0] = 1; arrayofintegers[1] = 2; arrayofintegers[2] = 3; arrayofintegers[3] = 4; arrayofintegers[4] = 5; 45

Manipulating Arrays An element of the array is accessed by accessing index at which element is stored int[] arrayofintegers = {1,2,3,4,5}; System.out.println(arrayOfIntegers[2]); 3 Console An array size can be obtained by asking for its length Used commonly in control statements (loops) int[] arrayofintegers = {1,2,3,4,5}; System.out.println(arrayOfIntegers.length); 5 Console 46

Multi-Dimensional Arrays An array can contain elements of other arrays Such an array is known as multi-dimensional array There is no limit is number of dimensions Arrays can be 2-dimensional, 3-dimensional, and n- dimensional int[][] arrayofintegers = new int[2][5]; 47

Multi-Dimensional Arrays 47

Manipulating Multi-Dimensional Arrays Multi-dimensional arrays are created like any other arrays Using the keyword new Using array initializers int[][] arrayofintegers = {{1,2,3,4,5},{6,7,8,9,10}}; Elements in multi-dimensional array are also accessed using their indices: int[][] arrayofintegers = {{1,2,3,4,5},{6,7,8,9,10}}; System.out.println(arrayOfIntegers[1][2]); 8 48

Overview: Summary Java Introduction History Portability Compiler Java Virtual Machine Garbage collection Java Syntax Identifiers Expressions Comments Java Basics Java types Primitives Objects Variables Operators Identity and equality Arrays What are arrays? Creating arrays Using arrays 2

Except where otherwise noted, this content is licensed under a Creative Commons Attribution-NonCommercial 3.0 License. For more information, please see http://creativecommons.org/licenses/by-nc/3.0/