Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Similar documents
Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Getting started with Java

COMP 202 Java in one week

Programming with Java

COMP 202 Java in one week

First Java Program - Output to the Screen

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Elementary Programming

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

2.8. Decision Making: Equality and Relational Operators

CS 177 Recitation. Week 1 Intro to Java

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

CMSC131. Introduction to your Introduction to Java. Why Java?

Lecture Set 2: Starting Java

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Lecture Set 2: Starting Java

What did we talk about last time? Examples switch statements

Introduction to Java & Fundamental Data Types

Introduction to Java Applications; Input/Output and Operators

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

COMP 202. Java in one week

PROGRAMMING STYLE. Fundamentals of Computer Science I

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Section 2.2 Your First Program in Java: Printing a Line of Text

CS 302: Introduction to Programming

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Programming with Java

Full file at

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

St. Edmund Preparatory High School Brooklyn, NY

Conditionals, Loops, and Style. Control flow thus far. if statement. Control flow. Common branching statement Evaluate a boolean expression

Introduction to Java. Java Programs Classes, Methods, and Statements Comments Strings Escape Sequences Identifiers Keywords

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Conditionals, Loops, and Style

Welcome to CSE 142! Zorah Fung University of Washington, Spring Building Java Programs Chapter 1 Lecture 1: Introduction; Basic Java Programs

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

Primitive Data, Variables, and Expressions; Simple Conditional Execution

Lab # 2. For today s lab:

Section 2: Introduction to Java. Historical note

CEN 414 Java Programming

Midterm Examination (MTA)

Computational Expression

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

COMP 110 Project 1 Programming Project Warm-Up Exercise

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

Question: Total Points: Score:

AP CS Unit 3: Control Structures Notes

printf( Please enter another number: ); scanf( %d, &num2);

Oct Decision Structures cont d

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

AP Computer Science Unit 1. Programs

CS102: Variables and Expressions

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2015

4. If the following Java statements are executed, what will be displayed?

Fundamentals of Programming. By Budditha Hettige

Darrell Bethea May 25, 2011

IT 374 C# and Applications/ IT695 C# Data Structures

COMP-202: Foundations of Programming. Lecture 2: Java basics and our first Java program! Jackie Cheung, Winter 2016

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Controls Structure for Repetition

CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

Java Bytecode (binary file)

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Full file at

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

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Fundamentals of Programming Session 4

Welcome to CSE 142! Whitaker Brand. University of Washington, Winter 2018

AP Computer Science A Unit 2. Exercises

Course Outline. Introduction to java

Chapter 2: Programming Concepts

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Eng. Mohammed S. Abdualal

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Section 2.2 Your First Program in Java: Printing a Line of Text

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Software Practice 1 Basic Grammar

Introduction to Computer Science Unit 2. Notes

Java Coding 3. Over & over again!

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

STUDENT LESSON A7 Simple I/O

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

COMP-202 Unit 2: Java Basics. CONTENTS: Printing to the Screen Getting input from the user Types of variables Using Expressions and Variables

Object-Oriented Programming

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Pace University. Fundamental Concepts of CS121 1

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

4 Programming Fundamentals. Introduction to Programming 1 1

Chapter 2 ELEMENTARY PROGRAMMING

Chapter 02: Using Data

Mr. Monroe s Guide to Mastering Java Syntax

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Eng. Mohammed Alokshiya

BASICS.

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

Transcription:

WIT COMP1000 Java Basics

Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java is a high level programming language» Provides many useful features that make it easier to write complex code» As opposed to low level languages that provide direct access to computer subsystems like memory but require much more care from programmers WIT COMP1000 2

Java Like most programming languages, Java programs are written using a fixed syntax» Syntax: a grammar that distinguished well formed statements from those that are not Special keywords and characters are used to tell the computer how to do what you want it to do Java forces the programmer to think as logically as the CPU» Step-by-step, following a strict order WIT COMP1000 3

Hello World public class HelloWorld { Tells Java that this file contains executable code } public static void main(string[] args) { } System.out.println("Hello World!"); "main" is where your program actually starts executing; for now simply use it to mean "start here" Print the line "Hello World" to the screen WIT COMP1000 4

Eclipse: New Project and Source File File menu -> New -> Java Project» Enter a Project name, for example: Hello World» Click Finish The project will show up in the left pane (Package Explorer) Right click on the project -> New -> Class» Enter a Name, for example: HelloWorld» Click the button labelled public static void main(string[] args)» Click Finish WIT COMP1000 5

Adding Code You can add your program code in between the curly braces after the main line For now, add the following line: System.out.println("Hello World!"); Note that you can ignore the line that starts with //» Lines that start with // are comments that are ignored by the compiler WIT COMP1000 6

Eclipse: Running Your Program When you are ready to test your program, you can run it directly in Eclipse Click the Run button» Or Run menu -> Run» Or (Windows) Ctrl-F11» Or (Mac) Shift-Cmd-F11 You'll be prompted to save your changes Then you'll see your program output in the Console pane at the bottom WIT COMP1000 7

Errors Save your work often! (Win Ctrl-s or Mac Cmd-s) If there are any errors in your syntax you will get a message indicating it» Normally click Cancel as there is no need to run the program if it was incorrect Error icons show up to the left of the line numbers where the errors are detected» Hover over the icon to get the error message» Also, go to the bottom pane then select the Problems tab to see a list of all errors detected WIT COMP1000 8

System.out.println() When you want to output text to the screen for the user to see, you use: System.out.println() This is a built-in Java method that makes it easy to print a line of text Syntax: System.out.println("Text") It automatically includes a special character at the end of your text so that the next time you use the method any text will begin on the following line WIT COMP1000 9

Notes about println() You can insert special characters into the output by putting a backslash in front of some normal characters» New line: \n» Horizontal tab: \t» Backslash: \\» Double quote: \" You can combine multiple pieces of text with the plus sign» We'll see why that's important soon WIT COMP1000 10

Examples System.out.println("Hello World!"); System.out.println("Howdy"); System.out.println("This is a tab:\t."); System.out.println("Hello" + " World!"); System.out.println("Avengers" + " assemble" + "!"); WIT COMP1000 11

Variables The first fundamental concept in programming is that of a variable» Variables are related to mathematical variables in algebra, but work quite differently Variables are stored in memory while the program is running» Every variable has a value that is stored in a particular memory location Each variable has a name that the programmer uses to access and modify that variable's value WIT COMP1000 12

Variables Each variable holds exactly one value Over time, as a program executes, the value of a variable can change» This is fundamentally different from algebraic variables which are used to represent one unknown value» Instead, programming variables store values so that we can use those values throughout a program WIT COMP1000 13

Variable Names In Java, variable names:» Must start with either a letter (uppercase or lowercase) or an underscore» Must contain only letters, digits, and underscores» Are case sensitive Examples: count, x, user_input2, hit_points Invalid names: 42, 5x, #yolo, file.cpp, a-b WIT COMP1000 14

Variable Declarations Every variable must be declared before you can use it in your program To declare a variable, you must give it a specific type:» int: integer (whole number), positive or negative» double: numbers with a fractional component» boolean: boolean value (true or false)» char: a single character WIT COMP1000 15

Syntax: TYPE NAME; Variable Declarations» The type comes first, then then variable name, followed by a semicolon» The semicolon tells Java that this declaration is done, and we'll see that many Java statements need one Examples:» int count;» int num_vals;» double average;» char first_initial; WIT COMP1000 16

Variable Initialization Before you can use a variable, you MUST give it a value Otherwise, your program won't know how to use the variable» In fact, it will have a random value based on what memory looked like before, which leads to unpredictable behavior Java will catch the error and notify you of it, but be careful of this in other languages WIT COMP1000 17

Variable Initialization You can initialize a variable when you declare it or you can do so afterwards Syntax after declaration: NAME = VALUE; Syntax during declaration: TYPE NAME = VALUE; Examples» count = 0;» ultimate_answer = 42;» int num_vals = 10;» double pi = 3.14159; WIT COMP1000 18

Example public class HelloWorld { } public static void main(string[] args) { int magic_points = 100; System.out.println("Number of magic points: " + magic_points); } WIT COMP1000 19

Printing Variables System.out.println() is used to output the current value of a variable Don't put the name of the variable in quotes» This is one of the most common mistakes made by new programmers Any values in quotes are printed out literally Any values not in quotes are assumed to be variable names WIT COMP1000 20

More Printing Notes You can mix literal text in quotes with variable names with the plus sign as we saw earlier If you don't want a new line automatically added to the end of your output message you can use System.out.print() instead» Otherwise it works the same as System.out.println() WIT COMP1000 21

Another Example public class HelloWorld { public static void main(string[] args) { int magic_points = 100; int hit_points = 200; System.out.print("Number of magic points: "); System.out.println(magic_points); System.out.println("Number of hit points: " + hit_points); } System.out.println("hit_points"); } WIT COMP1000 22

Sequential Execution Java programs start executing with the first line after the { after the main() line Each line is executed in order, one after the other until you get the } after the main() line We'll soon see how to affect this linear execution order, but even then programs execute one line at a time You have to train yourself to think one statement at a time» This is one of the single most important skills you can have as a novice programmer WIT COMP1000 23

Program Input We also need a way to get user input into our programs while they are running Java doesn't (easily) allow reading directly from System.in Instead, you use a Scanner object that handles reading the input and ensures that the type of data you read matches what you want» The syntax is weird at first, but you'll get use to it WIT COMP1000 24

Input with a Scanner First, you have to declare and initialize the Scanner object» Scanner input = new Scanner(System.in); Then you call different methods on the Scanner object to read different types of values from the keyboard» Read an int: variable = input.nextint();» Read a double: variable = input.nextdouble(); WIT COMP1000 25

Example import java.util.scanner; This line tells Java that you are going to use the Scanner public class InputOutput { public static void main(string[] args) { Scanner input = new Scanner(System.in); int magic_points = 100; int hit_points; System.out.print("Enter the number of hit points: "); hit_points = input.nextint(); } } System.out.print("Number of magic points: "); System.out.println(magic_points); System.out.println("Number of hit points: " + hit_points); WIT COMP1000 26

Notes about Scanner All input is automatically separated by whitespaces (spaces, new lines, tabs)» In other words, when you ask for a value from the Scanner it won't continue executing your program until a non-whitespace value is entered» Multiple input values can be separated on the same line by whitespaces In order to use the Scanner, you must include an extra line of code at the top of your source file: import java.util.scanner; WIT COMP1000 27

Comments In Java source code, you can (and will!) include comments that explain in plain English what is happening in the code There are two types of comments in Java Single line comments start with //» Everything after the // until the end of the line is ignored by the compiler Multi-line comments start with /* and end with */» Everything between the /* and the */ is ignored by the compiler WIT COMP1000 28

Commented Example import java.util.scanner; public class HelloWorld { public static void main(string[] args) { // set up the Scanner to work with user input Scanner input = new Scanner(System.in); // initialize the number of magic points to 100 int magic_points = 100; /* initialize the number of hits points based on * whatever the user types in */ int hit_points; System.out.print("Enter the number of hit points: "); hit_points = input.nextint(); } } // print out results System.out.print("Number of magic points: "); System.out.println(magic_points); System.out.println("Number of hit points: " + hit_points); WIT COMP1000 29

Wrap Up Java programs are executed one statement at a time, starting after main() and going down from there System.out.println() and System.out.print() are used to print values to the screen» Use double quotes to print literal words» Don't use quotes to print variables A Scanner object is used to read values from the user You should always include comments to explain your code for others who might read it WIT COMP1000 30