Lecture2: Java Basics Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Air Force Institute of Technology Electrical and Computer Engineering
Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
Written by: Dr. JJ Shepherd
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Sub and superclasses using extends
Java Syntax Primitive data types Operators Control statements.
CS102--Object Oriented Programming Review 1: Chapter 1 – Chapter 7 Copyright © 2008 Xiaoyan Li.
Static Class Members Wrapper Classes Autoboxing Unboxing.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Java Objects and Classes. 3-2 Object Oriented Programming  An OO program models the application as a world of interacting objects.  A typical Java program.
Day 4 Objectives Constructors Wrapper Classes Operators Java Control Statements Practice the language.
Principles of Computer Programming (using Java) Review Haidong Xue Summer 2011, at GSU.
JAVA PROGRAMMING PART II.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
6/6/2005 CS 3345: Algorithm Analysis and Data Structures Summer 2005, UT-Dallas 1 Specific topics of the Java Language Related to This Class Classes and.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
DAT602 Database Application Development Lecture 5 JAVA Review.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Object Oriented Programming: Java Edition By: Samuel Robinson.
Java Tutorial. Object-Oriented Programming Concepts Object –a representation of some item state  fields/members and should be encapsulated behavior 
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
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.
Page: 1 การโปรแกรมเชิงวัตถุด้วยภาษา JAVA บุรินทร์ รุจจนพันธุ์.. ปรับปรุง 15 มิถุนายน 2552 Keyword & Data Type มหาวิทยาลัยเนชั่น.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Inheritance The Basics in Java. Definition  A class that is derived from another class is called a subclass (also a derived class, extended class, or.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
Lecture4: Arrays Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
JAVA METHODS and CONSTRUCTORS. 2 JAVA Classes The class is the fundamental concept in JAVA (and other OOPLs) A class describes some data object(s), and.
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Operators in JAVA. Operator An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Variables and Types Java Part 3. Class Fields  Aka member variable, field variable, instance variable, class variable.  These are the descriptors of.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
A Java program consists of a set of class definitions, optionally grouped into packages. Each class encapsulates state and behavior appropriate to whatever.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Inheritance ndex.html ndex.htmland “Java.
Java Inheritance 1/13/2015. Learning Objectives Understand how inheritance promotes software reusability Understand notions of superclasses and subclasses.
Session 2 Operators, Decisions and Loops. Objectives Operators Casting data Decision marking structures Loops break, continue, return.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Programming Principles Operators and Expressions.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
CompSci 100E JB1.1 Java Basics (ala Goodrich & Tamassia)  Everything is in a class  A minimal program: public class Hello { public static void main(String[]
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CompSci 230 S Programming Techniques
Java Language Basics.
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Lecture 2: Data Types, Variables, Operators, and Expressions
03/10/14 Chapter 9 Inheritance.
Fundamental of Java Programming Basics of Java Programming
CMSC 202 Static Methods.
Starting JavaProgramming
null, true, and false are also reserved.
Character Set The character set of C represents alphabet, digit or any symbol used to represent information. Types Character Set Uppercase Alphabets A,
Introduction to Java Programming
An Introduction to Java – Part I, language basics
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Classes and Objects Static Methods
Presentation transcript:

Lecture2: Java Basics Bohyung Han CSE, POSTECH CSED233: Data Structures (2014F)

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Data Types Primitive data types 2 TypeBitsMinimum ValueMaximum Value byte short int32-2,147,483,6482,147,483,647 long64-9,223,372,036,854,775,8089,223,372,036,854,775,807 float e e+38 double e e+308 boolean1true / false char16

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Wrapper Class Each primitives has a corresponding class. String is an object rather than a primitive. 3 PrimitiveWrapper class byteByte shortShort intInteger longLong floatFloat doubleDouble booleanBoolean charCharacter String

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 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); 4

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 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" + "!" 5

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Arrays A data structure holding a group of variables under a single identifiers 6 byte[] anArrayOfBytes; int[] anArrayOfLongs; long[] anArrayOfLongs; float[] anArrayOfFloats; double[] anArrayOfDoubles; boolean[] anArrayOfBooleans; char[] anArrayOfChars; String[] anArrayOfStrings; int[] a; a = new int[2]; int[] b = {1, 2, 3, 4}; int bLength = b.length; // array declaration without assignment // specify the length of the array // array declaration with assignment // get the length of an array

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Operators Arithmetic Operators 7 OperatorDescriptionExample (A=10, B=20) +Adds values on either side of the operatorA + B will give 30 -Subtracts right hand operand from left hand operandA - B will give -10 *Multiplies values on either side of the operatorA * B will give 200 /Divides left hand operand by right hand operandB / 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 1B++ gives 21 --Decrease the value of operand by 1B-- gives 19

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Operators Relational Operators 8 OperatorDescriptionExample (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 (A > B) is not true. < Checks if the value of left operand is less than the value of right operand (A < B) is true. >= Checks if the value of left operand is greater than or equal to the value of right operand (A >= B) is not true. <= Checks if the value of left operand is less than or equal to the value of right operand (A <= B) is true.

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Operators Bitwise operators 9 OperatorDescriptionExample (A=60, B=13) &Binary AND Operator(A & B) will give 12 which is |Binary OR Operator(A | B) will give 61 which is ^Binary XOR Operator(A ^ B) will give 49 which is ~ Binary Ones Complement Operator (~A ) will give -61 which is in 2's complement form due to a signed binary number. <<Binary Left Shift OperatorA << 2 will give 240 which is >>Binary Right Shift OperatorA >> 2 will give 15 which is 1111 >>>Shift right zero fill operatorA >>>2 will give 15 which is

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Operators Logical operators 10 OperatorDescriptionExample &&Called Logical AND operator(A && B) is false ||Called Logical OR Operator(A || B) is true !Called Logical NOT Operator!(A && B) is true

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Operators Assignment operators 11 OperatorDescriptionExample =Simple assignment operatorC = A + B will assign value of A + B into C +=Add AND assignment operatorC += A is equivalent to C = C + A -=Subtract AND assignment operatorC -= A is equivalent to C = C - A *=*=Multiply AND assignment operatorC *= A is equivalent to C = C * A /=Divide AND assignment operatorC /= A is equivalent to C = C / A

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Control Flow if-then and if-then-else statements 12 Char assignGrade(int testscore) { int testscore = 76; char grade; if(testscore >= 90) grade = 'A';... else if(testscore >= 60) grade = 'D'; else grade = 'F'; return grade; }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Control Flow switch statement 13 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; } System.out.println(month_str); }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Loop for statement 14 // return {“January”, “February”, …, “December”} String[] month_strs = GetMonthStrings(); for (int i = 0; i < month_strs.length; i++) { System.out.println(month_strs[i]); }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Loop while statement 15 // return {“January”, “February”, …, “December”} String[] month_strs = GetMonthStrings(); int i = 0; while(i < month_strs.length) { System.out.println(month_strs[i]); i++; }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Loop do‐while statement 16 // return {“January”, “February”, …, “December”} String[] month_strs = GetMonthStrings(); int i = 0; do { System.out.println(month_strs[i]); i++; } while(i < month_strs.length)

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Branching break, continue and return statements 17 String padString(String str) { while(1) { if (str.length() >= 10) break;// get out of the loop else { str += “ ”; continue;// perform one more iteration } return str;// return a padded string }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Java Keywords abstractbooleanbreakbytecasecatchchar classconstcontinuedefaultdodoubleelse extendsfinalfinallyfloatforgotoif implementsimportinstanceofintinterfacelongnative newpackageprivateprotectedpublicreturnshort staticsuperswitchsynchronizedthisthrowthrows transienttryvoidvolatilewhile 18

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Java Output Formats System.out.print( +..); System.out.println( +..); 19 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); }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Java Constant Constant  Constants are like variables in that they have a name and store a certain type of information but unlike variables they CANNOT change. 20 final int SIZE = 1000;

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Class 21 public class Date { // data fields private int day; private String month; private int year; // constructors public Date() { day = 1; month = "January"; year = 2014; } public Date(int d, String m, int y) { day = d; month = m; year = y; } Anyone can use this class. Only class members can access. Anyone can call this constructor.

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Class 22 public Date(Date d) { this.day = d.getDay(); this.month = d.getMonth(); this.year = d.getYear(); } // accessor method public int getDay() { return day; } // mutator method public void setMonth(String str) { month = str; } Anyone can call this method. Calling accessor method

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Testing Class 23 public class TestDate { public static void main(String[] args) { Date date1 = new Date(); Date date2 = new Date(date1); Date date3 = new Date(11, “September”, 2013); System.out.println(“date2: ” + date2.getMonth() + “ ” + date2. getDay() + “ ” + date2.getYear()); date3.setMonth(“October”); System.out.println(“date3: ” + date3.getMonth() + “ ” + date3. getDay() + “ ” + date3.getYear()); } Create a Date object. Modify “month” field of date3 to “October.”

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Inheritance 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. 24 Class hierarchy

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Superclass (Base Class) 25 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; }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Superclass (Base Class) 26 // 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; }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Subclass (Derived Class) 27 public class MountainBike extends Bicycle { // the MountainBike subclass adds one field public int seatHeight; // the MountainBike subclass has one constructor public MountainBike(int startHeight,int startCadence, int startSpeed,int startGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } // the MountainBike subclass adds one method public void setHeight(int newValue) { seatHeight = newValue; } “MountainBike” inherits from “Bicycle.” It calls constructor of superclass.

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Inheritance 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. 28

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Overriding vs. Hiding Base class (super class) 29 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"); }

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 Overriding vs. Hiding Subclass (derived class) 30 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

CSED233: Data Structures by Prof. Bohyung Han, Fall 2014 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:  Java tutorial 

32