Data Types. Lecture2: Java Basics. Wrapper Class. Primitive data types. Bohyung Han CSE, POSTECH

Similar documents
Inheritance. The Java Platform Class Hierarchy

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

Inheritance, part 2: Subclassing. COMP 401, Spring 2015 Lecture 8 2/3/2015

Computer Science 210: Data Structures

Universiti Malaysia Perlis

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Strings, Strings and characters, String class methods. JAVA Standard Edition

CS260 Intro to Java & Android 03.Java Language Basics

CSC 1214: Object-Oriented Programming

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Programming Tutorial 1

Preview from Notesale.co.uk Page 9 of 108

The Java language has a wide variety of modifiers, including the following:

Introduction to Programming Using Java (98-388)

JAVA OPERATORS GENERAL

Lecture 2: Java & Javadoc

What is Inheritance?

Tony Valderrama, SIPB IAP 2009

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Learning the Java Language. 2.1 Object-Oriented Programming

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Programming Language Concepts: Lecture 2

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

CT 229. Java Syntax 26/09/2006 CT229

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Introduction and Review of Java: Part 2

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

Programming overview

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

3. Java - Language Constructs I

Operators and Expressions

Lesson: Classes and Objects

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

Program Fundamentals

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

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

1 Shyam sir JAVA Notes

Java Basic Programming Constructs

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

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

An overview of Java, Data types and variables

CSC Java Programming, Fall Java Data Types and Control Constructs

Handout 7. Defining Classes part 1. Instance variables and instance methods.

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

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

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

Java Primer 1: Types, Classes and Operators

Introduction To Java Programming

COMP 202 Java in one week

Language Features. 1. The primitive types int, double, and boolean are part of the AP

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

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

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

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

15CS45 : OBJECT ORIENTED CONCEPTS

Accelerating Information Technology Innovation

Chapter 2. Elementary Programming

Programming Language Concepts: Lecture 2

Lecture 2: Variables and Operators. AITI Nigeria Summer 2012 University of Lagos.

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

STRUCTURING OF PROGRAM

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

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.

Selected Questions from by Nageshwara Rao

CS313D: ADVANCED PROGRAMMING LANGUAGE

Index COPYRIGHTED MATERIAL

Expressions and Data Types CSC 121 Spring 2017 Howard Rosenthal

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

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

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

9 Working with the Java Class Library

Chapter 2: Using Data

JOSE LUIS JUAREZ VIVEROS com) has a. non-transferable license to use this Student Guide

CMPT 125: Lecture 4 Conditionals and Loops

CSE 21 Intro to Computing II. Post-Midterm Review

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following g roups:

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Chapter 2: Using Data

10/30/2010. Introduction to Control Statements. The if and if-else Statements (cont.) Principal forms: JAVA CONTROL STATEMENTS SELECTION STATEMENTS

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

Java Programming. Atul Prakash

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

The Arithmetic Operators

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

13 th Windsor Regional Secondary School Computer Programming Competition

SECTION II: LANGUAGE BASICS

Java for Python Programmers. Comparison of Python and Java Constructs Reading: L&C, App B

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

C# Programming for Developers Course Labs Contents

CS171:Introduction to Computer Science II

Introduction To Java Programming

Object-Oriented Concepts

Transcription:

Data Types Primitive data types (2015F) Lecture2: Java Basics Bohyung Han CSE, POSTECH bhhan@postech.ac.kr Type Bits Minimum Value Maximum Value byte 8 128 127 short 16 32768 32767 int 32 2,147,483,648 2,147,483,647 long 64 9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 32 1.40129846432481707e 45 3.40282346638528860e+38 double 64 4.94065645841246544e 324 1.79769313486231570e+308 boolean 1 true / false char 16 2 Wrapper Class Each primitives has a corresponding class. String is an object rather than a primitive. Primitive Wrapper class byte Byte short Short int Integer long Long float Float double Double boolean Boolean char Character String String Wrapper Class Wrap the primitive data type into an object Providing various functionalities Part of the java.lang package, which is imported by default Use of wrapper class Creating an object int x = 25; // x is a variable. Integer y = new Integer(33); // y is an object. Accessing value int z = x + y; // Wrong int z = x + y.intvalue(); // OK! Other operations int x = Integer.parseInt("1234"); String s = Integer.toString(1234); 3 4

String A sequence of characters An object, but often regarded as primitive data type Java provides the String class to create and manipulate strings. Creating string String greeting = "Hello world!"; Char[] helloarray = 'h', 'e', 'l', 'l', 'o', '.' ; String hellostring = new String(helloArray); String length String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); String concatenation string1.concat(string2); "My name is ".concat("rumplestiltskin"); "Hello," + " world" + "!" Arrays A data structure holding a group of variables under a single identifiers int[] a; a = new int[2]; int[] b = 1, 2, 3, 4; int blength = b.length; byte[] anarrayofbytes; int[] anarrayoflongs; long[] anarrayoflongs; float[] anarrayoffloats; double[] anarrayofdoubles; boolean[] anarrayofbooleans; char[] anarrayofchars; String[] anarrayofstrings; // array declaration without assignment // specify the length of the array // array declaration with assignment // get the length of an array 5 6 Operators Operators Arithmetic Operators Operator Description Example (A=10, B=20) + Adds values on either side of the operator A + B will give 30 Subtracts right hand operand from left hand operand A B will give 10 * Multiplies values on either side of the operator A * B will give 200 / Divides left hand operand by right hand operand B / A will give 2 % Divides left hand operand by right hand operand and returns remainder B % A will give 0 ++ Increase the value of operand by 1 B++ gives 21 Decrease the value of operand by 1 B gives 19 Relational Operators Operator Description Example (A=10, B=20) == Checks if the value of two operands are equal or not (A == B) is not true.!= Checks if the value of two operands are equal or not (A!= B) is true. > < >= <= Checks if the value of left operand is greater than the value of right operand Checks if the value of left operand is less than the value of right operand Checks if the value of left operand is greater than or equal to the value of right operand Checks if the value of left operand is less than or equal to the value of right operand (A > B) is not true. (A < B) is true. (A >= B) is not true. (A <= B) is true. 7 8

Operators Operators Bitwise operators Operator Description Example (A=60, B=13) & Binary AND Operator (A & B) will give 12 which is 0000 1100 Binary OR Operator (A B) will give 61 which is 0011 1101 ^ Binary XOR Operator (A ^ B) will give 49 which is 0011 0001 ~ Binary Ones Complement Operator (~A ) will give 61 which is 1100 0011 in 2's complement form due to a signed binary number. << Binary Left Shift Operator A << 2 will give 240 which is 1111 0000 >> Binary Right Shift Operator A >> 2 will give 15 which is 1111 >>> Shift right zero fill operator A >>>2 will give 15 which is 0000 1111 Logical operators Operator Description Example && Called Logical AND operator (A && B) is false Called Logical OR Operator (A B) is true! Called Logical NOT Operator!(A && B) is true 9 10 Operators Control Flow Assignment operators Operator Description Example = Simple assignment operator C = A + B will assign value of A + B into C += Add AND assignment operator C += A is equivalent to C = C + A = Subtract AND assignment operator C = A is equivalent to C = C A *= Multiply AND assignment operator C *= A is equivalent to C = C * A /= Divide AND assignment operator C /= A is equivalent to C = C / A if then and if then else statements Char assigngrade(int testscore) char grade; if(testscore >= 90) grade = 'A';... else if(testscore >= 60) grade = 'D'; else grade = 'F'; return grade; 11 12

Control Flow Loop switch statement void DisplayMonthString (int month) String month_str; switch (month) case 1: month_str = January ; break; case 2: month_str = February ; break;... default: month_str = InvalidMonthNumber ; break; for statement // return January, February,, December String[] month_strs = GetMonthStrings(); for (int i = 0; i < month_strs.length; i++) System.out.println(month_strs[i]); System.out.println(month_str); 13 14 Loop Loop while statement do while statement // return January, February,, December String[] month_strs = GetMonthStrings(); int i = 0; while(i < month_strs.length) System.out.println(month_strs[i]); i++; // return January, February,, December String[] month_strs = GetMonthStrings(); int i = 0; do System.out.println(month_strs[i]); i++; while(i < month_strs.length) 15 16

Branching break, continue and return statements String padstring(string str) while(1) if (str.length() >= 10) break; // get out of the loop else str += ; continue; // perform one more iteration Java 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 super switch synchronized this throw throws return str; // return a padded string transient try void volatile while 17 18 Java Output Java Constant Formats System.out.print(<string or var1> + <string or var2>..); System.out.println(<string or var1> + <string or var2>..); Constant Constants are like variables in that they have a name and store a certain type of information but unlike variables they CANNOT change. public class OutputExample1 public static void main (String[] args) int num = 123; System.out.println("Good night grace!"); System.out.print(num); System.out.println("num=" + num); final int SIZE = 1000; 19 20

public class Date // data fields private int day; private String month; private int year; Class // constructors public Date() Anyone can call this constructor. day = 1; month = "January"; year = 2015; public Date(int d, String m, int y) day = d; month = m; year = y; Anyone can use this class. Only class members can access. public Date(Date d) this.day = d.getday(); this.month = d.getmonth(); this.year = d.getyear(); // accessor method public int getday() return day; Class // mutator method public void setmonth(string str) month = str; Calling accessor method Anyone can call this method. 21 22 Testing Class Inheritance public class TestDate public static void main(string[] args) Date date1 = new Date(); Create a Date object. Date date2 = new Date(date1); Date date3 = new Date(11, September, 2015); Class hierarchy The Object class, defined in the java.lang package, defines and implements behavior common to all classes. Many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes. System.out.println( date2: + date2.getmonth() + + date2. getday() + + date2.getyear()); date3.setmonth( October ); System.out.println( date3: + date3.getmonth() + + date3. getday() + + date3.getyear()); Modify month field of date3 to October. Java class hierarchy 23 24

Superclass (Base Class) public class Bicycle // the Bicycle class has three fields public int cadence; public int gear public int speed; // the Bicycle class has two constructors public Bicycle() speed = 0; public Bicycle(int startcadence, int startspeed, int startgear) gear = startgear; cadence = startcadence; speed = startspeed; Superclass (Base Class) // the Bicycle class currently has three methods public void getcadence() return cadence; public void setgear(int newvalue) gear = newvalue; public void applybrake(int decrement) speed = decrement; 25 26 Subclass (Derived Class) Inheritance public class MountainBike extends Bicycle // the MountainBike subclass adds one field public int seatheight; MountainBike inherits from Bicycle. // the MountainBike subclass has one constructor public MountainBike(int startheight,int startcadence, int startspeed,int startgear) super(startcadence, startspeed, startgear); seatheight = startheight; It calls constructor of superclass. // the MountainBike subclass adds one method public void setheight(int newvalue) seatheight = newvalue; Properties A subclass inherits all the public and protected members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited. New fields, which are not in the superclass, can be declared in the subclass. You can write a new instance method in the subclass that has the same signature as the one in the superclass, thus overriding it. You can write a new static method in the subclass that has the same signature as the one in the superclass, thus hiding it. You can declare new methods in the subclass that are not in the superclass. You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using the keyword super. 27 28

Base class (super class) Overriding vs. Hiding public class Animal public static void testclassmethod() System.out.println("The static method in Animal"); public void testinstancemethod() System.out.println("The instance method in Animal"); Subclass (derived class) Overriding vs. Hiding public class Cat extends Animal public static void testclassmethod() System.out.println("The static method in Cat"); public void testinstancemethod() System.out.println("The instance method in Cat"); public static void main(string[] args) Cat mycat = new Cat(); Animal myanimal = mycat; Animal.testClassMethod(); myanimal.testinstancemethod(); The static method in Animal The instance method in Cat 29 30 Many Pre Created Classes Rule of thumb Before writing new program code to implement the features of your program you should check to see if a class has already been written with the features that you need. The Java API is Sun Microsystems's collection of pre built Java classes: http://java.sun.com/javase/7/docs/api/ Java tutorial http://docs.oracle.com/javase/tutorial/ 31 32