1.11k likes | 1.45k Views
introduction to java and simple programs practice
E N D
Hello World Program, Again // My First Program!! publicclass HelloWorld { public static void main(String[] args){ System.out.println(“Hello World!”); } }
Identifiers: Syntax • Identifiers are the words a programmer uses in a program • Identifier syntactic rules: • Can be made up of any length of • letters • digits • underscore character (_) • dollar sign ($) • Cannot begin with a digit • Java is case sensitive • Useranduserare completely different identifiers
Identifiers: Semantics • Identifiers names can come from the following sources • Fixed in Java as reserved words • public, class, static, void, method, … • Chosen by the programmer to denote something • HelloWorld, main, args • Chosen by a programmer whose code we use: • String, System, out, println
Naming style • The correctness of the program is not affected by the names used public class X7_65Tx { … } • Names play a central role in the readability of the program • They are part of its documentation • They should thus be chosen carefully • BankAccount, size, numberOfElements • Follow conventions in choosing names!
White Space • Spaces, blank lines, and tabs are collectively called white space • White space is used to separate words and symbols in a program • Extra white space is ignored • A valid Java program can be formatted many different ways • Programs should be formatted to enhance readability, using consistent indentation
Valid, but bad Indentation public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World!”) ;}}
Comments • Comments are ignored and are treated as white space • They should be written to enhance readability • Explain what a piece of code does (its interface) • Explain any special tricks, limitations, … • Java has three comment formats: • // comment to end of line • /* comment until closing */ • /** API specification comment */
Lesson 2 - Basic Java Elements Unit B2 - Variables and Data Types
Variables • A variable is a location in memory that can hold values of a certain datatype • Each variable must be declared before it is used • The declaration allocates a location in memory to hold values of this type • Variable types can be • primitive • reference to an object
VariableExample Program public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } }
VariableExample Program (2) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } x
VariableExample Program (3) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 3 x
VariableExample Program (4) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 3 x
VariableExample Program (5) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 4 x
VariableExample Program (6) public class VariableExample { public static void main(String[] args){ int x; x = 3; System.out.println(x); x = 4; System.out.println(x); } } 4 x
Primitive Data Types • A data type is defined by a set of values and the operators you can perform on them • The Java language has several predefined types, called primitive data types • The following reserved words represent the eight different primitive data types: • byte, short, int, long, float, double, boolean, char
Integers • There are four integer data types. They differ by the amount of memory used to store them
Floating Point • There are two floating point types
Characters • Acharvalue stores a single character from the Unicode character set • A character set is an ordered list of characters • ‘A’, ‘B’, ‘C’, … , ‘a’, ‘b’, … ,‘0’, ‘1’, … , ‘$’, … • The Unicode character set uses 16 bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages • The ASCII character set is a subset of Unicode • ASCII is the current standard (outside of Java)
Boolean • Abooleanvalue represents a true/false condition. • It can also be used to represent any two states, such as a light bulb being on or off • The reserved wordstrueandfalseare the only valid values for a boolean type
Variable Declarations • The syntax of a variable declaration is data-type variable-name; • For example • Multiple variables can be declared on the same line • Variables can be initialized (given an initial value) in the declaration int total; long total, count, sum; int total = 0, count = 20; double unitPrice = 57.25;
Variable Declaration Example public class DeclarationExample { public static void main (String[] args) { int weeks = 14; long numberOfStudents = 120; double averageFinalGrade = 78.6; System.out.println(weeks); System.out.println(numberOfStudents); System.out.println(averageFinalGrade); } }
More Variable Examples double pi, conversionRate, temprature; long salary; boolean isOn; char c; pi = 3.14159; isOn = false; c = ‘A’; salary = 34000; isOn = true;
Constants • We may declare that a variable is a constant and its value may never change. • Advantages: • readability • efficiency • error detection final double PI = 3.14159; final int CHINA_OLYMPICS_YEAR = 2008;
Lesson 2 - Basic Java Elements Unit B3 - Expressions
Assignment Statements • An assignment statement takes the following form variable-name = expression; • The expression is first evaluated • Then, the result is stored in the variable, overwriting the value currently stored in the variable
Arithmetic Operators • An operator is a mapping that maps one or more values to a single value: • Binary Operators: a + b adds a and b a - b subtracts b from a a * b multiplies a and b a / b divides a by b a % b the reminder of divining a by b • Unary Operator: -a The negation of a
Pounds to Kg conversion public class PoundsToKg { public static void main(String[] args){ double weightInPounds = 200.0; final double KILOS_IN_POUND = 0.455; double weightInKg; weightInKg = weightInPounds * KILOS_IN_POUND ; System.out.println(weightInKg); } }
Pounds to Kg conversion 2 public class PoundsToKg2 { public static void main(String[] args){ final double KILOS_IN_POUND = 0.455; System.out.println(200.0 * KILOS_IN_POUND); } }
Integer Division • When division is performed on integers (byte, short, int, long), the result is truncated to an integer. int j = 5; double x = 5.0, y; System.out.println(j / 2); // 2 System.out.println(x / 2.0); // 2.5 System.out.println(5 / 2); // 2 y = j / 2 ; // 2
Complex Expressions • Expressions can combine many operators and operands • Examples: x -34 weight * 2.73 2 * PI * r a - (7 – b) 1 + 2 + 3 + 4 (x + y) * (2 - z + (5 - q)) * -(1-x)
Operator Precedence • Multiplication, division, and remainder (%) have a higher precedence than addition and subtraction. • Operators with same precedence evaluate from left to right. • Parenthesis can be used to force order of evaluation.
Conversions • Data types can be mixed in an expression • When the expression is evaluated one type is converted to another • Data is converted to a wider type in three cases • assignment conversion • arithmetic promotion • casting • Can be converted to a narrower type only by casting • List of types from narrowest to widest: Narrow … Wide byte short int long float double
Conversion Examples double f, x; int j; f = 5; f = 5.0 / 2; f = x * j; f = 5 / 2; f = (float) j / 5; j = (int) f; j = (int) 5.0 / 2.0;
Lesson 2 - Basic Java Elements Unit B4 - Objects and Method Invocation
Reference Types • Variables can be declared to be of an object type. In this case they hold a reference to an object of this type (class). Turtle t; String myName; Date today; myName t today Memory
Creating Objects • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle();
Creating Objects (2) • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); today
Creating Objects (3) • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); today 12345
Creating Objects (4) • Objects are created by invoking a constructor of the class. Constructors may accept parameters. Date today; today = new Date(12345);// mSec since 1.1.1970 Turtle t = new Turtle(); t today 12345
Strings Strings are objects that are treated by the compiler in special ways: • Can be created directly using “xxxx” • Can be concatenated using + String myName = “John Jones”; String hello; hello = “Hello World”; hello = hello + “!!!!”; int year = 2008; String s = “See you in China in “ + year;
Method invocations • You may invoke methods on an object. Methods may receive parameters. • Methods may also return values. Turtle leonardo = new Turtle(); leoardo.moveForward(100); String lennon = “John Lennon”; int len = lennon.length(); char initial = lennon.charAt(5);
APIs • To use an object you only need to know its application programmer interface (API). • The API of an object class includes a description of: • all available constructors and methods and what they do • the parameters they take and the values that they return • The API is usually given in a special format called javadoc.
Class Libraries • A class library is a collection of classes that we can use when developing programs • There is a standard class library that comes with every Java environment. • Class Libraries are organized into packages • java.net, java.lang, java.io, ... • To use classes from a package you must either • Import the package • Or, use a fully qualified class name import java.io.*; File f = new File(“John”); java.io.File f = new java.io.File (“John”);
RandomNumbers.java import java.util.Random; public class RandomNumbers { public static void main (String[] args){ Random generator = new Random(); int num = generator.nextInt(); System.out.println ("A random int: " + num); num = generator.nextInt(); System.out.print(“Another one: “ + num); } }
Lesson 2 - Basic Java Elements Unit B5 - Input and Output