Object-Oriented Programming: Computer Science Year II
Object-Oriented Programming: Computer Science Year II
Programming
Computer Science Year II
Compiled by: Gebreigziabher A.
1
Basics of Java Programming
2
2.1 Structure of Java Program
[Comments]
[Namespaces]
[Classes]
[Objects]
[Variables]
[Methods]
3
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 not6 return any value.
*The basic elements of Java are:
1.Keywords (Reserved Words)
2.Identifiers
3.Literals
4.Comments
7
* 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.
8
Keyword Purpose
boolean declares a boolean variable or return type [True/False - 0/1]
byte declares a byte variable or return type
char declares a character variable or return type [Single character]
double declares a double variable or return type
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 declares a long integer variable or return type
while begins a while loop
for begins a for loop
do begins a do while loop
switch tests for the truth of various possible cases
break prematurely exits a loop
continue prematurely return to the beginning of a loop
case one case in a switch statement
9
11
Identifiers are tokens that represent names of variables,
methods, classes, packages and 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
12
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
13 of characters
enclosed by double quotes. Example: String str=“Hello World”;
Comments are notes written to a code for documentation
purposes. Those text are not part of the program and
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
14
*/.
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
15
*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)
16
Data Type Size Range
boolean 1 byte Take the values true and false only (0/1).
17
• Constants
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);
} 18
}
*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 Equivalent To
= n = 25
+= n += 25 n = n + 25
-= n -= 25 n = n - 25
*= n *= 25 n = n * 25
/= n /= 25 n = n / 25
%= n %= 25 n = n % 25
19
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);
}
} 20
*Java has five basic arithmetic operators. ( +, -, *, /, %)
21
*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));
}
} 22
Operator Name Description
x <= y Less than or equal to True if x is less than or equal to y, otherwise false.
x >= y Greater than or equal to True if x is greater than or equal to y, otherwise false.
23
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( “”); 24
}}}
* C++ provides three logical/conditional operators for combining logical
expressions. Logical operators evaluate to True or False.
}
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");
26
} }}
Operator Use Description
++ x++ Increments x by 1; evaluates to the value of x before it was incremented
() []
++ -- !
* / %
+ -
> >= < <=
== !=
&&
||
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)) 29
}}
//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);
33
}}
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
} 34
}
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.
35
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
36
} //end of class IO