E N D
Session Two Basics of Java Programming 1
2.1 Structure of Java Program [Comments] [Namespaces] [Classes] [Objects] [Variables] [Methods] 2.2 Java IDE(Integrated Development Environment) There are several Java IDEs [NetBeans, BlueJ, JCreator…] 2
import java.io.*; //Java class for I/O public class Hello { //Java class called Hello // My first java program public static void main(String[] args) { //Java main function //prints the string "Hello world" on screen System.out.println("Hello world!"); /*Prints Hello world to the console on new line */ }} * The "public static void" key words in the main function has the following meanings *public – specifies that the method is accessible to all other classes and to the interpreter. *static – this keyword specifies that the method is one that is associated with the entire class. *It is not associated with objects belonging to the class *void – specifies that the method does not return any value. 5
*The basic elements of Java are: 1.Keywords (Reserved Words) 2.Identifiers 3.Literals 4.Comments 6
*Keywords are predefined identifiers reserved by Java for a specific purpose. *There are 48 reserved keywords currently defined in the Java language. These keywords cannot be used as names for a variable, class or method [Identifiers]. *The keywords const and goto are reserved but not used. 7
Keyword Purpose declares a boolean variable or return type [True/False - 0/1] declares a byte variable or return type declares a character variable or return type [Single character] declares a double variable or return type boolean byte char double float declares a floating point variable or return type short declares a short integer variable or return type void declare that a method does not return a value int declares an integer variable or return type long while for do switch break continue case default declares a long integer variable or return type begins a while loop begins a for loop begins a do while loop tests for the truth of various possible cases prematurely exits a loop prematurely return to the beginning of a loop one case in a switch statement default action for a switch statement 8
Continued… if else try catch finally class abstract extends execute statements if the condition is true signals the code to be executed if an if statement is not true attempt an operation that may throw an exception handle an exception declares a block of code guaranteed to be executed signals the beginning of a class definition declares that a class or method is abstract specifies the class which this class is a subclass of declares that a class may not be subclassed or that a field or method may not be overridden declares that this class implements the given interface final implements import permit access to a class or group of classes in a package instanceof interface native new package private tests whether an object is an instanceof a class signals the beginning of an interface definition declares that a method is implemented in native code allocates a new object defines the package in which this source code file belongs declares a method or member variable to be private 9
Continued… protected declares a class, method or member variable to be protected public declares a class, method or member variable to be public return returns a value from a method declares that a field or a method belongs to a class rather than an object static super a reference to the parent of the current object synchronized Indicates that a section of code is not thread-safe this a reference to the current object throw throw an exception throws declares the exceptions thrown by a method transient This field should not be serialized volatile Warns the compiler that a variable changes asynchronously 10
Identifiers are tokens that represent names of variables, methods, interfaces etc. Rules for Java identifiers. • Begins with a letter, an underscore “_”, or a dollar sign “$”. • Consist only of letters, the digits 0-9, or the underscore symbol “_” • Cannot use Java keywords/reserved words like class, public, private, void, int float, double… • Cannot use white spaces classes, packages and 11
oLiterals are tokens that do not change or are constant. The different types of literals in Java are: • Integer Literals: decimal (base 10), hexadecimal (base 16), and octal (base 8). Example: int x=5; //decimal int x=0127; //octal int x=0x3A; //hexadecimal or int x=OX5A; • Floating-Point Literals: represent decimals with fractional parts. Example: float x=3.1415; • Boolean Literals: have only two values, true or false (0/1). Example: boolean test=true; • Character Literals: represent single Unicode characters. A Unicode character is a 16-bit character set that replaces the 8-bit ASCII character set. Example: char ch=‘A’; • String Literals: represent multiple/sequence of characters enclosed by double quotes. Example: String str=“Hello World”; 12
Comments purposes. compiler ignores executing them. They add clarity and code understandability. Java supports three types of comments: 1. C++-Style/Single Line Comments – Starts with // •Everything on a single line after // is ignored by the compiler. E.g. // This is a C++ style or single line comments 2. C-Style: Multiline comments – Starts with /* and ends with */ •Everything between /* and */ is ignored by the compiler. E.g. /* This is an example of a C-style or multiline comments */ 3. Documentation Comments: is used to produce an HTML file that documents your program. The documentation comment begins with a /** and ends with a */. E.g. /** This is documentation comment */. are notes written to a code for documentation Those text are not part of the program and 13
2.5.1 Variables *A variable is an item of data used to store state of objects. *A variable has a data type and a name. The data type indicates the type of value that the variable can hold. The variable name must follow rules for identifiers. *Declaring Variables To declare a variable is as follows, datatype name; int x; *Initializing Variables [At moment of variable declaration] int x = 5; // declaring AND assigning char ch = ‘A’; //initializing character *Assigning values to Variables [After variable declaration] int x; // declaring a variable x = 5; // assigning a value to a variable 14
*There are eight built-in (primitive) data types in the Java language. • 4 integer types (byte, short, int, long) • 2 floating point types (float, double) • 1 Boolean (boolean) • 1 Character (char) 15
Data Type Size Range boolean Take the values true and false only (0/1). 1 byte byte -27to 27-1 1 byte short -215to 215-1 2 bytes int -231to 231-1 4 bytes long -263to 263-1 8 bytes float -231to 231-1 4 bytes double -263to 263-1 4 bytes char 256 characters (Stores single character): ‘x’ 8 bytes String Sequence of characters :“Hello world” 1 byte 16
In Java, a variable declaration can begin with the final keyword. This means that once an initial value is specified for the variable, that value is never allowed to change. Example: final float pi=3.14; final int max=100; //or final int max; max=100; public class Area_Circle { public static void main(String args[]) { final float pi=3.14; float area=0; //initialize area to 0 float rad=5; area=pi*rad*rad; //compute area System.out.println(“The Area of the Circle: ”+area); } } 17
*An operator is a symbol that operates on one or more arguments to produce a result. 2.6.1 Assignment Operator (=) *The assignment operator is used for storing a value at some memory location (typically denoted by a variable). *Var=5 assigning a value to a variable using =. Operator = += -= *= /= %= Example n = 25 n += 25 n -= 25 n *= 25 n /= 25 n %= 25 Equivalent To n = n + 25 n = n - 25 n = n * 25 n = n / 25 n = n % 25 18
class Assign { public static void main( String args[] ) { int a=1; int b=2; int c=3; a+=5; b*=4; c+=a*b; c%=6; System.out.println(“a=”+ a); System.out.println(“b=”+ b); System.out.println(“c=”+ c); } } 19
*Java has five basic arithmetic operators. ( +, -, *, /, %) Operator Name Use Description Addition + op1 + op2 Adds op1 and op2 Subtraction - op1 - op2 Subtracts op2 from op1 Multiplication * op1 * op2 Multiplies op1 by op2 Division / op1 / op2 Divides op1 by op2 Remainder Computes the remainder of dividing op1 by op2 % op1 % op2 20
*Open a new file in the editor and type the following script. class ArithmeticOperators { public static void main(String args[]) { int x=10; int y=20; int z=25; System.out.println( “The value of x+y is “ + (x+y)); System.out.println( “The value of z-y is “ + (z-y)); System.out.println( “The value of x*y is “ + (x*y)); System.out.println( “The value of z/y is “ + (x/y)); System.out.println( “The value of z%y is “ + (z%x)); } } 21
Relational Operators six relational/comparison operators Operator Name Description x < y Less than True if x is less than y, otherwise false. x > y Greater than True if x is greater than y, otherwise false. Less than or equal to x <= y True if x is less than or equal to y, otherwise false. x >= y Greater than or equal toTrue if x is greater than or equal to y, otherwise false. x == y Equal True if x equals y, otherwise false. x != y Not Equal True if x is not equal to y, otherwise false. 22
class RelationalOperators { public static void main(String args[]) { int x=10; int y=20; System.out.println( “Demonstration of Relational Operators in Java”); if(x<y) { System.out.println( “The value of x is less than y “); } else if(x>y) { System.out.println( “The value of x is greater than y “); } else if(x==y) { System.out.println( “The value of x is equal to y”) } else { System.out.println( “”); } } } 23
*C++ provides three logical/conditional operators for combining logical expressions. Logical operators evaluate to True or False. Operator Name Example ! Logical Negation (NOT) !(5 == 5) // gives False && Logical AND 5 < 6 && 6 < 6 // gives False || Logical OR 5 < 6 || 6 < 5 //gives True public class LogicalOps { public static void main(String[] args) { int x=6; int y=6; int z=5; System.out.println(!(x==y)); //Prints False b/c true condition reversed by negating System.out.println(z < 10 && y <5); //Prints False b/c Both conditions are not true System.out.println(z < 6 || x > 7); //Prints True b/c one of the condition is True } } 24
import java.util.Scanner; //import statement for accepting input from keyboard public class LogOps { public static void main(String[] args) { double mark; Scanner input = new Scanner( System.in ); //Create Scanner to obtain input from command window System.out.println( "Enter Student Mark: "); // prompt user to enter mark mark = input.nextDouble(); // obtain user input from keyboard if(mark<0 || mark>100) { System.out.println("Invalid Input! Mark Must be between 0 & 100"); } else if(mark>80 && mark<=100) { System.out.println("A"); } else if(mark>=60 && mark<80) { System.out.println("B") ; } else { System.out.println(“F"); 25 } } }
Operator ++ Use Description Increments x by 1; evaluates to the value of x before it was incremented x++ Increments x by 1; evaluates to the value of x after it was incremented ++ ++x Decrements x by 1; evaluates to the value of x before it was decremented -- x-- Decrements x by 1; evaluates to the value of x after it was decremented -- --x *Example Let x=5 Operator ++ Name Example Auto Increment (prefix) ++x + 10 // gives 16 ++ Auto Increment (postfix) x++ + 10 // gives 15 -- Auto Decrement (prefix) --x + 10 // gives 14 -- Auto Decrement (postfix) x-- + 10 // gives 15 26
public class IncDec { public static void main(String[] args) { // Prefix increment and postfix increment operators. int c; c = 5; // assign 5 to c //Pre incrementing and post incrementing. System.out.println(c++ ); // prints 5 then post increments c = 5; // assign 5 to c System.out.println(++c ); // pre increments then prints 6 //Pre decrementing and post decrementing. c = 5;// assign 5 to c System.out.println(c-- ); // prints 5 then post decrements c = 5; // assign 5 to c System.out.println(--c ); // pre decrements then prints 4 } // end main } // end class IncDec 27
Highest ( ) [ ] ++ ! -- * + % / - > < <= >= != == && || Lowest Example: c=Math.sqrt((a*a)+(b*b)); Sytem.out.println(“Result: ”+c); if((mark<=0) || (mark=>100)) Sytem.out.println(“Mark must be in the range 0 and 100!”); if((mark=>85) && (mark<=90)) Sytem.out.println(“You Score A Grade!”); 28
*A statement is one or more line of code terminated by semicolon (;). Example: int x=5; System.out.println(“Hello World”); *A block is one or more statements bounded by an opening & closing curly braces that groups the statements as one unit. Example: public static void main(String args[]) { int x=5; int y=10; char ch=‘Z’; System.out.println(“Hello ”); System.out.println(“World”); //Java Block of Code System.out.println(“x=”+x); System.out.println(“y=”+y); System.out.println(“ch=”+ch); 29 }
* Type casting enables you to convert the value of one data from one type to another type. * E.g. (int) 3.14; // converts 3.14 to an int to give 3 (long) 3.14; // converts 3.14 to a long to give 3 (double) 2; // converts 2 to a double to give 2.0 (char) 122; // converts 122 to a char whose code is 122 (z) (short) 3.14; // gives 3 as a short public class TypeCasting { public static void main(String[] args) { float x=3.14; int ascii = 65; System.out.println(“Demonstration of Simple Type Casting"); System.out.println((int) x); //3 System.out.println((long) x); //3 System.out.println((double) x); //3.0 System.out.println((short) x); //3 System.out.println((char) ascii); //A } } 30
//Input Statements(Use Scanner class found in import java.util.Scanner package) import java.util.Scanner; public class IO { public static void main(String[] args) { String name; int x; float y; //Variable declarations double z; Scanner input = new Scanner( System.in ); /*Create Scanner in main function to obtain input from command window */ System.out.println("Enter Your Name: "); //prompt user to enter name name= input.nextLine(); // Obtain user input(line of text/string) from keyboard System.out.println("Enter x, y, z:"); //prompt user to enter values of x, y & z x= input.nextInt(); // Obtain user integer input from keyboard y= input.nextFloat(); // Obtain user float input from keyboard z= input.nextDouble(); // Obtain user float input from keyboard //Output Statements(Use the statement System.out.println() & System.out.println()) System.out.println("Your Name is: "+name); System.out.println("The Value of x is: "+x); System.out.println("The Value of y is: "+y); System.out.println("The Value of z is: "+z); } } 31
//Input Statements(Use BufferReader class found in import import.java.io package) import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class GetInputFromKeyboard { public static void main( String[] args )throws IOException { BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ); String name; int age; String str; System.out.print("Please Enter Your Name:"); name=dataIn.readLine(); System.out.print("Please Enter Your Age:"); str=dataIn.readLine(); //to read an input data age=Integer.parseInt(str); //convert the given string in to integer //Output Statement (Using System.out.println()) System.out.println("Hello "+ name +"! Your age is: "+age); 32 } }
import java.util.Scanner; public class JavaIO { public static void main( String args[] ) { // main method begins program execution String studID; double gpa; Scanner input = new Scanner( System.in ); /*Create Scanner to obtain input from command window */ System.out.println( "Enter Student ID: "); // prompt user to enter ID studID=input.nextLine(); // obtain user input from keyboard System.out.println( "Enter GPA: "); // prompt gpa=input.nextDouble(); // obtain user input System.out.println("Student ID: "+studID); // Displaying Student ID to Console Screen System.out.println("Student GPA: "+gpa); // Displaying GPA to Console Screen } 33 }
Here's a sample program, public class OutputVariable { public static void main( String[] args ){ int value = 10; char x; //To input character from key board ch= (char) System.in.read(); x = ‘A’; System.out.println( value ); //Prints 10 System.out.println( “The value of x=“ + x ); //Prints The value of x= A System.out.println( “Hello“ ); //Prints Hello on new line System.out.print( “World”); //Adds No new line, prints World after Hello } } System.out.println() vs. System.out.print() System.out.println() – appends a newline at the end of the data to output. System.out.print() – Doesn’t print on new line. 34
Import java.util.Scanner; Public class IO { Public static void main(String[] args) { int x, y, sum, dif, pro, quo; Scanner input=new Scanner (System.in); //create scanner object input to get input from user System.out.println(“Enter any 2 integers: ”); x=input.nextInt(); y=input.nextInt(); sum=x+y; dif=x-y; pro=x*y; Quo=(double) x/y; System.out.println(“The Sum x+y= ”+sum); System.out.println(“The Difference x-y= ”+dif); System.out.println(“The Product x*y= ”+pro); System.out.println(“The Quotient x/y= ”+quo); } //end of main } //end of class IO 35