CS111: PROGRAMMING LANGUAGE II Computer Science Department
Lecture 1(b): Java Basics (I)
Lecture Contents 2
Java basics Input/output Variables
Expressions
Computer Science Department
Your first Java program.. 3
// indicates a comment. class keyword Java is case sensitive braces { , } delimit a class body main Method
“Everything must be in a class” There are no global functions or global data. Computer Science Department
Basic language elements 4
Text I/O 5
Standard output. Flexible
OS abstraction for output. In Java, applications use the standard output object (System.out) to display text on terminal.
Computer Science Department
Command line output 6
Multiple line O/P Formatting output
public class TestIO { public static void main(String[] args) { System.out.println(“Welcome to java”); System.out.println(“Welcome to \n java”); System.out.print(“Welcome to”); System.out.println(“java”); System.out.printf(“%s\n%s\n“, “Welcome to”,”java”); }
input is received from Terminal window. Input entered while program is executing.
Computer Science Department
Reading values 11
use : import java.util.Scanner; Define an object of the Scanner class: Scanner input = new Scanner(System.in);
input values: num1 = input.nextInt();
Display after calculation: System.out.printf(“the square is : %d \n”, num1*num1);
Computer Science Department
example 12
Computer Science Department
example 13
Computer Science Department
variables 14
Declaration, memory allocation, initialization data type
variable name
int total = 0; int count, temp, result; Multiple variables can be created in one declaration
Computer Science Department
Constants 15
A “constant variable” is an identifier that is similar to a variable except that it holds one value for its entire existence Why constants:
give names to otherwise unclear literal values facilitate changes to the code prevent inadvertent errors
In Java: final double PI = 3.14159265;
Computer Science Department
Arithmetic Expressions 16
An expression is a combination of operators and operands Arithmetic expressions (we will see logical expressions later) are essentially special methods applied to numerical data objects: compute numeric results and make use of the arithmetic operators: Addition Subtraction Multiplication Division Remainder
+ * / % Computer Science Department
Assignment-related Operators 17
Increment and decrement operators: ++, -Assignment operators: +=, -=, *=, /= these three expressions have the same effect
count
=
count + 1;
count
+= 1;
count
++;
these two expressions have the same effect
count
=
count - 10;
count
-= 10; Computer Science Department
Operator Precedence 18
What is the order of evaluation in the following expressions? a + b + c + d + e 1 2 3 4
a + b * c - d / e 3 1 4 2
a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1 Computer Science Department