0% found this document useful (0 votes)
44 views34 pages

Object-Oriented Programming: Computer Science Year II

The document discusses the basics of object-oriented programming in Java, including the structure of a Java program with classes, objects, and methods. It explains Java programming elements like keywords, identifiers, literals, comments, variables, data types, operators, and provides examples of basic Java code syntax. The document serves as an introduction to foundational concepts in Java for computer science students.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
0% found this document useful (0 votes)
44 views34 pages

Object-Oriented Programming: Computer Science Year II

The document discusses the basics of object-oriented programming in Java, including the structure of a Java program with classes, objects, and methods. It explains Java programming elements like keywords, identifiers, literals, comments, variables, data types, operators, and provides examples of basic Java code syntax. The document serves as an introduction to foundational concepts in Java for computer science students.
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 34

Object-Oriented

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]

2.2 Java IDE(Integrated Development Environment)


There are several Java IDEs [NetBeans, BlueJ, JCreator…]

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

default default action for a switch statement


Continued…
if execute statements if the condition is true
else signals the code to be executed if an if statement is not true
try attempt an operation that may throw an exception
catch handle an exception
finally declares a block of code guaranteed to be executed
class signals the beginning of a class definition
abstract declares that a class or method is abstract
extends specifies the class which this class is a subclass of
declares that a class may not be subclassed or that a field or method
final
may not be overridden
implements declares that this class implements the given interface
import permit access to a class or group of classes in a package
instanceof tests whether an object is an instanceof a class
interface signals the beginning of an interface definition
native declares that a method is implemented in native code
new allocates a new object
package defines the package in which this source code file belongs
10
private declares a method or member variable to be private
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
static
object
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

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).

byte 1 byte -27 to 27 -1

short 2 bytes -215 to 215-1


int 4 bytes -231 to 231-1
long 8 bytes -263 to 263-1

float 4 bytes -231 to 231-1

double 4 bytes -263 to 263-1


char 8 bytes 256 characters (Stores single character): ‘x’
String 1 byte Sequence of characters :“Hello world”

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. ( +, -, *, /, %)

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 op1 % op2 Computes the remainder of dividing op1 by op2

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 True if x is less than y, otherwise false.

x>y Greater than True if x is greater than y, otherwise false.

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.

x == y Equal True if x equals y, otherwise false.

x != y Not Equal True if x is not 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.

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
} 25

}
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

++ ++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

*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
27
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 28
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)) 29

Sytem.out.println(“You Score A Grade!”);


* 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);
30
}
* 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
}
31
}
//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); 32

}}
//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

You might also like