Exercise on Java Basics

Slides:



Advertisements
Similar presentations
STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
March 2005Java Programming1. March 2005Java Programming2 Why Java? Platform independence Object Oriented design Run-time checks (fewer bugs) Exception.
Session 5 java.lang package Using array java.io package: StringTokenizer, ArrayList, Vector Using Generic.
1 Course Lectures Available on line:
Class Library, Formatting, Wrapper Classes, and JUnit Testing
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Packages and Libraries M Taimoor Khan
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
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.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Java Programming: From Problem Analysis to Program Design, 5e Chapter 2 Basic Elements of Java.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
1 Programming Java Java Basics. 2 Java Program Java Application Program Application Program written in general programming language Applet Program running.
Autoboxing A new feature in Java 5.0. Primitive types and classes In Java we have primitive types –boolean, char, byte, short, int, long, float, double.
1 CS 007: Introduction to Computer Programming Ihsan Ayyub Qazi.
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.
Review and Java Questions 13 June Classes, objects, attributes, methods In Java, by convention a class name begins with Uppercase: Coffee, String.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
1 Chapter 2: Java Fundamentals cont’d Spring Lory Al Moakar.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Object Oriented Programming Lecture 2: BallWorld.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
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.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Key Words / Reserved Words
JAVA MULTIPLE CHOICE QUESTION.
Review of Java … or maybe not.
Formatting Output & Enumerated Types & Wrapper Classes
Chapter 4 – Fundamental Data Types
Yanal Alahmad Java Workshop Yanal Alahmad
University of Central Florida COP 3330 Object Oriented Programming
CSC 1051 – Data Structures and Algorithms I
Multiple variables can be created in one declaration
Exercise on Java Basics
Classes, Libraries & Packages
Switch, Rounding Errors, Libraries
Java Programming: From Problem Analysis to Program Design, 4e
Advanced Programming in Java
INPUT STATEMENTS GC 201.
Chapter 2.
Advanced Programming in Java
Advanced Programming Behnam Hatami Fall 2017.
Coding Standard & Javadoc
CMSC 202 Static Methods.
5 Variables, Data Types.
Unit-2 Objects and Classes
An Introduction to Java – Part I, language basics
Chapter 2: Basic Elements of Java
The Building Blocks Classes: Java class library, over 1,800 classes:
Java Variables, Types, and Math Getting Started
Classes and Objects 5th Lecture
MSIS 655 Advanced Business Applications Programming
Java Classes and Objects 3rd Lecture
Arrays and Collections
Java for IOI.
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
Classes and Objects Static Methods
Introduction to Primitives
Java’s Central Casting
Using java libraries CGS3416 spring 2019.
Chapter 2: Java Fundamentals cont’d
Presentation transcript:

Exercise on Java Basics

Complete and Correct this Code public _________ Coin { private int value; public Coin( int value ) { ____________________ ; } public void getValue( ) { return value; public String toString( ) { System.out.println( value . "-Baht");

Packaging and Commenting Code package coinpurse; /** * Coin represents money with an integer value. * @author Bill Gates */ public class Coin { private int value; * Initialize a new coin object. * @param value is the value of the coin public Coin( int value ) { this.value = value; }

Packages Java uses packages to organize classes. Packages reduce size of name space and avoid name collisions Example: The Java 8 API has... 2 classes named "Date" 1 class and 4 interfaces named "Element" 1 class and 1 interface named "List" (java.util.List & java.awt.List)

Name these Packages java.lang Core classes of the Java language Object, String, System, Integer, Double, Math, Thread. java.io Classes for input and output InputStream, BufferedReader, File, OutputStream java.util Date/time classes, collections, utilities Calendar, Date, List, ArrayList, Set, Arrays, Formatter, Scanner java.time New date and time classes. LocalDate, LocalTime, Month, Duration

Package you never need to import java.lang java compiler always "import"s all classes in this package, so you don't need to.

Package Name using Domain Name The domain for the JUnit testing framework is: http://junit.org The Java package for JUnit is org.junit What should be the Java package for each of these? org.log4j.subpack Log4J logging framework. The URL is http:/log4j.org org.jfree JFreeChart plotting library for Java: http://www.jfree.org com.lloseng OCSF networking framework: http://www.lloseng.com

Resolving Ambiguity: Date class There is a Date class in java.util and java.sql In this code, which Date class will Java use? java.util.Date (because it is imported first) java.sql.Date (because it is imported last) depends on Java implementation compile error import java.util.*; // has java.util.Date import java.sql.*; // has java.sql.Date class Ambiguous { Date today = new Date( ); ... }

Resolving Ambiguity (2) How can you fix this problem (2 solutions)? Solution 1: Solution 2: import java.util.*; import java.sql.*; // (1) class Ambiguous { // (2) __________ today = new _____________; }

Resolving Ambiguity (3) How can you resolve this problem (2 solutions)? Solution 1: import a specific class Solution 2: use the full path in Java code import java.util.*; import java.sql.*; import java.util.Date; // Solution (1) class Ambiguous { java.util.Date today = new java.util.Date( ); // (2) ... }

How to convert a String to a number? How to get the "int" value from String s? String s = "1234"; // At least 3 possible solutions: int n1 = int n2 = Scanner scanner = int n3 = Methods in the Integer class can also be used to evaluate strings with different base (radix) such as binary or hexadecimal. Example: Integer.parseInt( "4AE7", 16)

How to convert number to String? How to create a String for a number n? int n = 100; String s = n; // error: must convert to string // At least 4 possible solutions: String s1 = String s2 = String s3 = String s4 =

How to convert number to String? How to convert a number n to a String? int n = 100; String s = n; // error: must convert to string // At least 4 possible solutions: String s1 = Integer.toString( n ); String s2 = "" + n; String s3 = String.valueOf( n ); String s4 = String.format( "%d", n );

String Concatenation What is output by each of these? Why? int m = 11; int n = 22; System.out.println( m + n ); System.out.println( "The sum is " + m + n ); System.out.println( m + n + " is the sum" ); System.out.println( "The sum is " +(m + n) );

Java Primitive Data Types Java has 8 primitive data types These are not classes or objects. No properties. Name Values Examples true false true, false character 'a', 'A', '1', 'ก', 'ค', '\t' 8-bit integer -127, ..., -1, 0, 1, ..., 127 16-bit integer -32768 ... 0 ... 32767 32-bit integer -400 47 20000000 64-bit integer -1234567890L 0L 888L 32-bit decimal 3.14159F 0.0F -2.5E-8F 64-bit decimal 3.14159265358979E234

Write an equals( ) method for Coin equals is true only if: 1) parameter is a Coin 2) parameter (as Coin) has same value as this Coin public class Coin { private int value; public boolean equals( Object arg ) { //1. test for null //2. test if arg is really a Coin //3. cast arg to type Coin //4. compare the values }

How to Convert Primitive to Object? A List (like ArrayList) can only contain objects. How can we convert a primitive type to an object? List mylist = new ArrayList( ); int id = 51651111; // this works in Java 5+, because java converts it mylist.add( id ); // How to convert id to an object type?

Wrapper Classes Primitive Wrapper boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double double root = Math.sqrt( 2.0 ); Double d1 = new Double( root ); // same thing: automatic boxing Double d2 = root; // print as a string out.println( d2.toString( ) ); // static method to make a string out.println( Integer.toString( 2 ) );

Wrapper to convert to/from String int n = 2*3*5*7*11*13*17*19*23*29*31; // how to convert n to a String? String product = _______________________; String s = "2.5"; // how to convert s to a double? double d = __________________________;

Range limits for numeric types What is the largest "int" value? What is the smallest "long" value? What is the range (smallest, biggest) of double? int biggest = long smallest = double minsize = double maxsize =

What happens beyond the limit? int n = Integer.MAX_VALUE; n = n + 1; System.out.println( n ); double d = Double.MAX_VALUE; d = d + 1; System.out.println( d ); d = d * 1.000001;

C# is different "int", "float", "double" are struct types. // This is C# int n = int.MaxValue; String s = "The biggest integer is " + n.ToString( ) ; // range checking is enforced n = n + 1; System.OverflowException: Arithmetic operation resulted in an overflow.

How to parse? How can you read 2 integers from this String? // String containing some integers String s = "12 45"; // How to get the integers from s?

Careful parsing A String contains some words, but we don't know how many. How would you parse the words? // String containing some words String s = "Java 8 is complicated"; // How to get each word from s?

3 ways to parse a String 1. String.split( regex ) String [] args = s.split("\\s+"); // splits the string at whitespace chars 2. java.util.Scanner (powerful but slow) Scanner in = new Scanner( s ); while ( in.hasNext( ) ) String arg = in.next( ); 3. StringTokenizer (old but faster) StringTokenizer tokens = new StringTokenizer(s); while ( tokens.hasMoreElements( ) ) String arg = tokens.nextToken( );