Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014.

Slides:



Advertisements
Similar presentations
Programming Languages and Paradigms The C Programming Language.
Advertisements

IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
True or false A variable of type char can hold the value 301. ( F )
Access to Names Namespaces, Scopes, Access privileges.
Structure of a C program
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
CMT Programming Software Applications
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
COMP 14 Introduction to Programming Miguel A. Otaduy May 18, 2004.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 30, 2005.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
COP INTERMEDIATE JAVA Review of COP2250 Concepts.
General Features of Java Programming Language Variables and Data Types Operators Expressions Control Flow Statements.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Java Software Solutions Lewis and Loftus Chapter 5 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. More Programming Constructs.
CPS120: Introduction to Computer Science
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
Introduction to Java Java Translation Program Structure
Java Programming The Language of Now & the Future* Lecture 0 An Introduction to Java Syntax for Non-C Programmers John Morris Department of Electrical.
Copyright Curt Hill Variables What are they? Why do we need them?
CSC 212 Object-Oriented Programming and Java Part 2.
Java™ How to Program, Early Objects Version, 8/e © by Pearson Education, Inc. All Rights Reserved.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Java Nuts and Bolts Variables and Data Types Operators Expressions Control Flow Statements Arrays and Strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
By Mr. Muhammad Pervez Akhtar
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
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.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
Presentation By :- Nikhil R. Anande ( ) Electronic & Communication Engineering. 3 nd Year / 5 th Semester FACULTY GUIDE : RAHIUL PATEL SIR MICROCONTROLLER.
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[]
Today… Continue Building Expressions: –Literals –Constants –Casting –Array Declaration –Operators and Operator Precedence –Keywords Winter 2016CMPE212.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Information and Computer Sciences University of Hawaii, Manoa
Definition of the Programming Language CPRL
Programming in Java Sachin Malhotra, Chairperson, PGDM-IT, IMS Ghaziabad Saurabh Chaudhary, Dean, Academics, IMS Ghaziabad.
Sachin Malhotra Saurabh Choudhary
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
CS180 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Multiple variables can be created in one declaration
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 3: Understanding C# Language Fundamentals
CET 3640 – Lecture 2 Java Syntax Chapters 2, 4, 5
Java - Data Types, Variables, and Arrays
Chapter 8 JavaScript: Control Statements, Part 2
Module 2: Understanding C# Language Fundamentals
elementary programming
Control Structure Chapter 3.
Presentation transcript:

Basic Java Syntax COMP 401, Spring 2014 Lecture 2 1/14/2014

AverageHeightApp – take 2 Same as before, but with Eclipse. – Eclipse Workspace – Creating new project – Creating a new package – Creating new class

Comments Single line comments: // This is a comment. Multiple line comments: /* All of these lines. Are commented. */

A Word About Types Value Types Integers Real numbers Booleans Character Reference Types String Array Objects typed by their class Classes themselves Values types are defined entirely by their value. Reference types are structures in memory. Address in memory uniquely identifies them. The “value” of a variable that holds a reference type is this address.

Value Types Integers –byte, short, int, long – Difference is in size (1, 2, 4, or 8 bytes) – No “unsigned” version – Decimal (255), hexidecimal (0xff), and binary (0b ) literal formats Real Numbers –float, double – Difference is in precision. Characters –char – Characters in Java are 16-bit Unicode values – Literals use single-quote: ‘c’ – Non-printable escape sequence: ‘\u####’ where # is hex digit. Example: ‘\u00F1’ for ñ Logical –boolean – Literals are true and false

Packages, classes, and methods, oh my! A package is a collection of classes. – Defined by a “package” statement at the beginning of a source code file. Example: package lec02.ex01; All classes defined in the file belong to that package. A class is a collection of functions (for now). – Defined by “class” keyword followed by a block of code delimited by curly braces. – Example: public class { /* Class definition. */ } A method is just another name for a function or procedure and is a named sequence of Java statements. – Defined within a class. – Can be “called”, or “invoked” with parameters – Syntax: a method header or signature followed by a block of code delimited by curly braces.

Method Signature Almost everything you need to know about a method is in its signature. – 5 parts to a method signature Access modifier –public, private, protected – If unspecified, then “package” access. Method type –static or default (i.e., not specified) – The keyword static indicates that this is a “class method”. – If the keyword static is not present, then this is an “instance method”. Return type – The type of value returned by the method as a result. – If there is no result, then this is indicated by the keyword void. Method name – Must start with a letter, $, or _ – Can contain letters, numbers, $, or _ (no spaces or other punctuation) Parameter list – In parenthesis, comma-separated list of parameter typed variable names. » If the method has no parameters, then just: () – Each parameter variable name is preceded by a type declaration.

Method Signature Examples public static void main(String[] args) int foo (int a, MyType b, double c) protected static void bar() static String toUpperCase(String s) static private Secret my_secret()

Until we know a little more… All of the methods in my examples today are going to be public class methods. – This means their signatures will include the words: public static

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Declarations of local variables Assignment Conditional Loop Method call Return statement Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Declaration of local variables Assignment Conditional Loop Method call Return statement Statement Blocks – One or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Local variable declaration Syntax: type name; type name1, name2, name3; type name = value; A local variable is valid within the block of statements where the declaration occurs. – This is known as the scope of the variable. – The declaration must occur before the variable is used. Parameter names are local variables that are in scope for the entire method body.

Variable Names Variable names should start with a letter and can contain letters, digits, $, or _ – Can not start with digit – Can not contain whitespace or punctuation other than $ or _ In general, use of punctuation in variable names is discouraged. – Case sensitive – Can not be a keyword Legal: – foo, bar, a_variable, var123 Legal but not considered good: – var_with_$, _badness Illegal: – 1var, while, break, this has whitespace

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Declarations of local variables Assignment Conditional Loop Method call Return statement Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Assignment Syntax: variable = expression; Note: single equals for assignment. Left hand side must be some sort of variable that can be assigned. Expression must produce a value that matches the type of the variable.

Expressions A sequence of symbols that can be evaluated to produce a value. – Can be used wherever a value is expected. Types of expressions: – Literal values: 123, ‘c’, “a string”, true – Variable name: a_variable – Value retrieved from an array: my_array[3] – Class/object fields: Math.PI – Value as a result of a method call: foo() – Compound expressions formed by applying an operator: 4+3*2

Operators Unary: +, -, !, ++, -- Arithmetic: +, -, /, *, % Relational: ==, !=, >, >=, <, <= Boolean: &&, || Ternary: ?: – expression ? if_true : if_false Bitwise: ~, >, >>>, &, |, ^ Be aware of precedence – Can be controlled by explicitly grouping with () Be aware of context – Some operators do different things depending on the types of the values they are applied to.

Assignment and Unary Operators Most numeric operators have an “assignment” form. – Easy syntax for applying the operator to a variable and assigning the result back to the same variable. – Examples: a += 3// Equivalent to a = a + 3 b *= 4// Equivalent to b = b * 4 Unary operators ++ and – – Used with integer typed variables to increment and decrement. – Usually used as a statement unto itself: a++;// Equivalent to a = a + 1; b--; // Equivalent to b = b – 1;

Importing JAR files into a project Save JAR file somewhere. Create a new project in Eclipse. Right click the src folder in the project and choose, “Import…” Choose the type General->Archive and click Next Browse for and select the JAR file. Click Finish

lec02.ex2.Example2 Variable declarations for value types Integer math vs. Real math Ternary operator Operator precedence Boolean operator shortcut

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Variable declaration Assignment Conditional Loop Method call Return statement Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Conditional Execution: if-else if-else 22 if (expression) { block } else if (expression) { block } else { block }

if example if (score > 90) { System.out.println(“You got an A!”); } else if (score > 80) { System.out.println(“You got a B.”); } else if (score > 70) { System.out.println(“You got a C?”); } else if (score > 60) { System.out.println(“You got a D :-(“); } else { System.out.println(“You failed”); }

Conditional Execution: switch switch (expression) { case value: statements break; case value: statements break;... default: statements } Works with basic value data types Works with String as of Java 7 Execution starts at first matching case value or default if provided and no case matches Continues until break statement or end of switch.

Switch Example switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("Vowel"); break; default: System.out.println("Consonant"); }

lec02.ex3.Example3 if and switch demo Variables scoped within block Style hint: – Don’t test boolean expression against true/false Testing real numbers with epsilon bounds

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Variable declaration Assignment Conditional Loop Method call Return statement Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Loops: while while (expression) { block } do { block } while (expression);

while example int sum = 0; int n = 1; while (n < 11) { sum += n; n++; } System.out.println(“The sum of 1 to 10 is: “ + sum);

Loops: for for (init; test; update) { block }

for example int sum = 0; for(int n=1; n<11; n++) { sum += n; } System.out.println(“The sum of 1 to 10 is: “ + sum); Note that variable n is declared as part of init expression in for loop. – This is a common programming idiom if loop variable is only needed for the loop. – Scope of variable is limited to the loop block.

Loop odds and ends To skip to next iteration of loop body use “continue” statement. To break out of the loop body use “break” statement.

Example while and for while and for equivalence scope of for loop variable break / continue

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Variable declaration Assignment Conditional Loop Method call Return statement Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Calling Methods Calling a class method defined in the same class: methodName(parameters); Calling a class method defined in a different class (same package): ClassName.methodName(parameters); Calling a class method defined in a different package: PackageName.ClassName.methodName(parameters) In the above “parameters” is a comma separated list of values. – A value can be also be an expression that results in a value. – Must match in number and type according to method’s signature. A method call that returns a value (i.e., not a “void” method) can be part of an expression. int max_times_min = max(a, b, c) * min(a, b, c);

Inside a method The body of a method is a sequence of statements. A statement ends in a semi-colon – Types of statements: Variable declaration Assignment Conditional Loop Method call Return statement Blocks – Zero or more statements enclosed in curly braces { } – Allowed anywhere a single statement is allowed. And vice versa

Return Syntax: return expression; Ends execution of a method and returns the value of the expression as the result of the method. – Must match type declared in method signature. – If method return type is “void”, then simply: return;

lec02.ex5.Example5 Calling methods Compound expressions as part of method call to provide parameter value. Returning from middle of method Unreachable code error Calling method in same/different class, same/different package

Import Directive Maps class names from other packages into current name space. – Convenient if going to use one or more class names repeatedly. Map all names from a package: import package.*; Map a specific name from a package: import package.name ;

Example5OtherRevisited import Math revisited – Classes in java.lang package are automatically imported.