CS 134: Introduction To Java

1y ago
10 Views
2 Downloads
3.68 MB
43 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Troy Oden
Transcription

CS 134:Introduction to JavaSlide content based on http://www.cs.cmu.edu/ mjs/courses/121-F14-W/Java4Python.pdf

Announcements & Logistics Lab 9 Boggle : Due tonight/tomorrow @ 11pm Lots of of ce hours Come talk to us if you have questions!HW 9 available today, due Mon 5/9 @ 11pmCovers “advanced” topics from recent lectures Lab 10 Selection Sort in Java (next Mon/Tue)No pre-lab work; hope most of you will start and nish during yourlab session Final exam reminder: Sunday, May 22 @ 9:30 AM Course evals next Friday 5/13 (bring a laptop to class if possible)fifiDo You Have Any Questions?

May the 4th Be With You Working on partner labs be like — hopefully none of you had to resortto git push --force!

Last TimeBrie y reviewed searching algorithms: O(log n): binary search runtime in a sorted array-based list O(n): linear searching runtime in an unsorted listDiscussed two classic sorting algorithms: O(n log n): merge sort runtime O(n 2): selection sort runtimeWhat about (extra) space for sorting? O(n): naive merge sort O(1): selection sortTime-space tradeoff!fl

Today Discuss how to run programs in Java Learn about Java syntax Take a closer look at data types in JavaGoals of next 4-5 lectures: Understand the key similarities and differences between Pythonand other programming languages (Java) Review basic features of Python in preparation for nal exam Gain con dence in our programming abilities Help ease the transition to CS 136 (and beyond!)fi Begin discussing Javafi

Python vs. JavaPythonJava Powerful language used by manyprogrammers Features for making commonprogramming tasks relativelysimple Features for building large-scalesystems design Can run programs as scripts orinteractively Must be "compiled" and run fromterminal Dynamically typed: Run-timeerror when variables are usedincorrectly Statically typed: compile-timeerror when variables are usedincorrectly Good t for teachingprogramming to new computerscientists Good t for large softwareprojects, but steep learning curvefiPowerful language used by manyprogrammersfi

Hello, World!Python in Week 1:Python in Week 11:Java:

Hello, World!Python:Java:

Hello, World!Python:Java:

Running Our Code Python is an interpreted language The Python interpreter runs through our code line by line andexecutes each command Other interpreted languages: PHP, R, Ruby, and JavaScriptJava is a compiled language* The Java compiler converts our code into machine code that theprocessor can execute Compiled languages require code to be manually compiledbefore execution Other compiled languages: C, C , Haskell, Rust, and GoInterpreted languages were once signi cantly slower than compiledlanguages. But that gap is shrinking.*Technically Java is both interpreted and compiled, but we can ignore that detail for now.fi

Using the Java CompilerJava source les are always named file .java To compile, type:javac file .java Compilers detect and report syntax errorsbefore execution Compiler creates class les: file .class Code is executed by typingjava file (without the .class extension)fi fiThe compiler converts our Java source codeinto compiled byte code which is faster torun (hence the performance bene ts)fi

Important Java Rules The le name must be the same as the class name (Hello.java). Every object in Java must have an explicit type. Every Java program that we want to execute must have a mainmethod: public static void main(String[] args) Blocks of code contained within {} (versus indentation in Python) Statements end with ; (versus new line in Python)fiEvery Java program must de ne a class, and all code is inside a class.fi

Important Java Rules Every Java program must de ne a class, and all code is inside a class. The le name must be the same as the class name (Hello.java). Every object in Java must have an explicit type. Every Java program that we want to execute must have a mainmethod: public static void main(String[] args) Blocks of code contained within {} (versus indentation in Python) Statements end with ; (versus new line in Python)De ne a class called Hello.Notice the curly brace.fififiThis curly brace closesthe one on line 1.

Important Java Rules Every Java program must de ne a class, and all code is inside a class. The le name must be the same as the class name (Hello.java). Every object in Java must have an explicit type. Every Java program that we want to execute must have a mainmethod: public static void main(String[] args) Blocks of code contained within {} (versus indentation in Python) Statements end with ; (versus new line in Python)De nes the main method. Similar to sayingif name “ main ” in Python.fififiClosing curly braceOpening curly brace

Important Java Rules Every Java program must de ne a class, and all code is inside a class. The le name must be the same as the class name (Hello.java). Every object in Java must have an explicit type. Every Java program that we want to execute must have a mainmethod: public static void main(String[] args) Blocks of code contained within {} (versus indentation in Python) Statements end with ; (versus new line in Python)fifiPrint “Hello, World!” to the terminal.Statements end with a ;

Public, Private, Protected public indicates to the Java compiler that this is a method thatanyone can call Java enforces several levels of security on methods (also variables andclasses): public, protected, and private Similar to and methods in Python, but more strictly enforced

static static indicates that this is a method that is part of the class, but is not a method for anyone instance of the class (static exists in both Java and Python!) Most methods we used in Python required an instance of the class in order for the methodto be called: Example: s.upper() (where s is a string and upper() is a method in the string class) With a static method, the object to the left of the . is a class, not an instance of the class. For example the way that we would call the main method directly is: Hello.main( ). Similar to Python modules (such as random) that don’t require an instance Example: random.randint(0,15)

void void tells the Java compiler that this method will not return a value void means “no type” Roughly analogous to omitting the return statement in a Python method(or having an implicit return of None)

String args[ ] Our main method takes as input an array (denoted by []) of Stringscalled args This is used for handling command-line arguments but we won'tworry about that now Since everything in Java must have a type, we also have to tell the compilerthat the types of values stored in our array are Strings Recall that arrays are a lot like lists in Python

System.out and System.inSystem is a Java class Within the System class we nd the object named out The out object is the standard output stream for this program. The inobject is the standard input stream. We’ll come back to that soon. The println method prints a string with a newline character at the end Anywhere in Python that you used the print( ) function you will usethe System.out.println( ) method in Javafi

Moving on

Programming Language Features Basic features: Data Types Reading user input Loops ConditionalsWe have extensively studied all of thesefeatures in Python. Let’s compare andcontrast with Java.Advanced topics: Classes Interfaces Collections Graphical User Interface Programming

Programming Language Features Basic features: Data Types Reading user input Loops ConditionalsLet’s start with data types and readinguser input.Advanced topics: Classes Interfaces Collections Graphical User Interface Programming

Basic Data Types All data types in Python are objects Two types of data types in Java: primitive (non-objects) and Objects Example: int (lowercase) and Integer (uppercase) The bene t of primitive data types is fast operations We’ll mostly use the Object versions and let the compiler handleconversions to primitives for usJava data types:fi Implemented using classes and methods just like our LinkedList

Simple Example Consider this Python script: temp.py What does it do?

Simple Example Consider this Python script: temp.py What does it do?Asks user to enter a temperature in Fahrenheit and converts thestring input to oat Does the computation to convert temperature to Celsius Prints resultfl

Simple Example Same program in Java: TempConv.java

Simple ExampleComments in Java start with //compared to # in Python Same program in Java: TempConv.java

Simple ExampleJava import statements are similar tofrom module import xxxstatements in Python Java uses import statements to tell the compiler what classes to use

Simple ExampleLines 6-8 are variable declarations, whichde ne the name and type of our variables. Oncedeclared, the types cannot be changed.fi Java is statically typed. Thus, all variables must be declared with a name andtype before they are used. Common convention is to declare variables at the topof our methods/classes.

Simple ExampleNote: Removing these lines will cause thecompiler to report several errors. Let’s try to compile: javac TempConv.java

The compiler will report severalerrors (sometimes repeatedly)when we try to compile ourprogram after removing ourvariable declarations.

Simple ExampleOn Line 8 we give our Scanner the name in.On Line 10, we initialize our Scanner object with theparameter System.in to read input from the user.Note: Always use new when initializing new objects. After declaring a Scanner object named in, we also have toinitialize it before using it (like calling init () in Python).

flSimple ExampleOn Line 11 we print a prompt to the screen.On Line 12, we use our Scanner to read theinput value as a Double (a double precisionoating point number) and store the value as fahr. and System.out.println are like print in Python.in.nextDouble() automatically reads the user input as a Double (like usinginput() in Python and then converting to float)System.out.print

An Aside: Using the Java Scanner Since Java is strongly typed, we have to be extra careful when readinginput from the user to make sure it is of the expected type The Scanner class provides methods for making sure the next value(like an iterator!) is of the expected type Here are some methods for the Java Scanner class

Simple ExampleOn Line 14 we perform the calculation to convert.On Line 15 we print the results. Arithmetic calculations in Java and Python are very similar wrt syntax When we print, we use the operator to perform string concatenation

Simple Example]]] Before running our program, we compile using javacjavac TempConv.java To run, we use javajava TempConv

Recap: Python vs. Java]Java:Python: ]Step 1: Prepare to read input from user.

Recap: Python vs. Java]Java:Python: Step 2: Prompt user for input.]

Recap: Python vs. Java]Java:Python:]Step 3: Read user input and convert to oat/double (that is, a numberwith a decimal point).fl ]

Recap: Python vs. JavaJava:]Python: ]Step 4: Perform conversion to Celsius.

Recap: Python vs. JavaJava:]Python:] Step 5: Print result.

An Aside: Java GUIs Java has more built-in support for makingGUIs and supporting graphical objects Here is a graphical version of ourprogram

Today Begin discussing Java Discuss how to run programs in Java Learn about Java syntax Take a closer look at data types in Java Goals of next 4-5 lectures: Understand the key similarities and differences between Python and other programming languages (Java) Review basic features of Python in preparation for final exam Gain confidence in our programming abilities

Related Documents:

134-1400 LS EP Switch 265-1002 134-1402 LS EP Switch 265-1006 Original Part No. Mfg. Description Part No. 134-1403 LS EP Switch 265-1005 134-1404 LS EP Switch 265-1002 134-1405 LS EP Switch 265-1004 134-1406 LS EP Switch 265-1003 134-1407 LS EP Switch 265-1006 134-1452 LS Pressure Elec. Switch 134-1451 134-1456 LS Pressure Elec. Switch 134-1451 .

java.io Input and output java.lang Language support java.math Arbitrary-precision numbers java.net Networking java.nio "New" (memory-mapped) I/O java.rmi Remote method invocations java.security Security support java.sql Database support java.text Internationalized formatting of text and numbers java.time Dates, time, duration, time zones, etc.

Java Version Java FAQs 2. Java Version 2.1 Used Java Version This is how you find your Java version: Start the Control Panel Java General About. 2.2 Checking Java Version Check Java version on https://www.java.com/de/download/installed.jsp. 2.3 Switching on Java Console Start Control Panel Java Advanced. The following window appears:

22913553 m adamowicz jorge alberto 134 668 6219298 f adaro tomasa petrona 134 668 36905048 m addamo marcos eduardo 134 668 35232822 m addamo maximiliano nicolas 134 668 . 45073074 f aguilera rocio 134 668 111423 f aguilera julia delia 134 668 46689312 m aguilera joaquin 134 668 38937886 m aguilera fernando 134 668

3. _ is a software that interprets Java bytecode. a. Java virtual machine b. Java compiler c. Java debugger d. Java API 4. Which of the following is true? a. Java uses only interpreter b. Java uses only compiler. c. Java uses both interpreter and compiler. d. None of the above. 5. A Java file with

CORE JAVA TRAINING COURSE CONTENT SECTION 1 : INTRODUCTION Introduction about Programming Language Paradigms Why Java? Flavors of Java. Java Designing Goal. Role of Java Programmer in Industry Features of Java Language. Installing Java Di

Java EE Java Platforms Java Card: Smart card version Java ME (Micro Edition): Embedded systems, e.g. Mobile handheld Java SE (Standard Edition): Desktop application development Java EE (Enterprise Edition): Enterprise distributed application software Java EE add standards and libraries to SE for fault- tolerant, distributed, multi-tier based components

besteht aus der Java-API (Java Application Programming Interface) und der Java-VM (Java Virtual Machine). Abbildung 1: Java-Plattform Die Java-API ist eine große Sammlung von Java-Programmen, die in sog. Pakete (packages) aufgeteilt sind. Pakete sind vergleichbar mit Bibliotheken in anderen Programmiersprachen und umfassen u.a.