0% found this document useful (0 votes)
12 views

Chapter 2-BasicsinJavaProgramming-Electrical

oop note

Uploaded by

michael.tegegn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Chapter 2-BasicsinJavaProgramming-Electrical

oop note

Uploaded by

michael.tegegn
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

EEEg3142

Object Oriented Programming

Department of CSIT, Software


Engineering
AASTU
October, 2017
Chapter 2
Introduction to Java Elements

2
Outline
Introduction
 Sample Java Program
 Java Identifiers
Java Keywords
Number types, strings, constants
Operators
Type Conversion/Casting
I/O, Conditional statements and loops
Arrays

3
Definition and History of java
Java is an object-oriented programming language.
Java was developed by James Gosling and his team at
Sun Microsystems in California. Sun formally announced
Java at an industry conference in May 1995.
In 1991 Sun funded an internal corporate research project
code-named Green. The language was based on C and
C++ and was originally intended for writing programs that
control consumer appliances such as toasters,
microwave ovens, and others.
The language was first called Oak, named after the oak
tree outside of Gosling’s office, but the name was already
taken, so the team renamed it Java.
4
Java Application and Java Applet
Java can be used to program two types of programs:
Applets and applications.
Applets: are programs called that run within a Web
browser. That is, you need a Web browser to execute
Java applets.
Applets allow more dynamic and flexible
dissemination of information on the Internet
Java Application: is a complete stand-alone program
that does not require a Web browser.
A Java application is analogous to a program we write
in other programming languages.

5
Basics of a Typical Java Environment
Java programs normally undergo five phases
 Edit
 Programmer writes program (and stores program on disk)
 Compile
 Compiler creates bytecodes from program
 Load
 Class loader stores bytecodes in memory
 Verify
 Verifier ensures bytecodes do not violate security requirements
 Execute
 Interpreter translates bytecodes into machine language

6
Basics of a Typical Java Environment(cont’d)

7
Basics of a Typical Java Environment(cont’d)

8
Basics of a Typical Java Environment(cont’d)

Java source
code

Java
Java bytecode
compiler

Bytecode
interpreter

Machine
code

9
Basics of a Typical Java Environment(cont’d)

Phase 1: Creating a Program


 consists of editing a file with an editor program (editor).
 You type a Java program (source code) using the editor, make
any necessary corrections and save the program.
 A file name ending with the .java extension indicates that the file
contains Java source code

Phase 2: Compiling a Java Program into Bytecodes


 Use the command javac (the Java compiler) to compile a
program.
 E.g.: To compile a program called Welcome.java, you would
type javac Welcome.java in the command window of your
system

10
Basics of a Typical Java Environment(cont’d)
 If the program compiles, the compiler produces a .class file called
Welcome.class that contains the compiled version of the program.
 The Java compiler translates Java source code into bytecodes that
represent the tasks to execute in the execution phase (Phase 5).
 Byte codes are executed by the Java Virtual Machine (JVM).
 Virtual machine (VM) is a software application that simulates a
computer, but hides the under-lying operating system and hardware
from the programs that interact with the VM.
 Java’s bytecodes are portable. Unlike machine language, which is
dependent on specific computer hardware, bytecodes are platform-
independent instructions. That is why Java is guaranteed to be
Write Once, Run Anywhere.
 The JVM is invoked by the java command.
 For example, to execute a Java application called Welcome, you
would type the command java Welcome in a command window to
invoke the JVM, which would then initiate the steps necessary to
execute the application. This begins Phase 3. 11
Basics of a Typical Java Environment(cont’d)

Phase 3: loading: placing the program in memory before


executing it.
 The class loader takes the .class files containing the program’s
bytecodes and transfers them to primary memory.
 The .class files can be loaded from a disk on your system or over
a network (e.g., your local college or company network, or the
Internet).

Phase 4: Bytecode Verification


 bytecode verifier examines their bytecodes to ensure that they
are valid and do not violate Java’s security restrictions.
 Java enforces strong security, to make sure that Java programs
arriving over the network do not damage your files or your
system (as computer viruses and worms might).

12
Basics of a Typical Java Environment(cont’d)

Phase 5: Execution
 The JVM executes the program’s bytecodes, thus performing the
actions specified by the program.
 In early Java versions, the JVM would interpret and execute one
bytecode at a time; Java programs execute slowly.
 Today’s JVMs typically execute bytecodes using a combination of
interpretation and so-called just-in-time (JIT) compilation.
 The JVM analyzes the bytecodes as they are interpreted, searching
for hot spots— parts of the bytecodes that execute frequently.

Integrated development environment (IDE) combines


these steps into a single task.
 A graphical user interface is available for editing, compiling,
linking, and running the application.
 Example: NetBeans, Eclipse, Jbuilder, …
13
Java Features
Java is:
 Object Oriented
 Simple
 Architectural-neutral: Java compiler generates an architecture-
neutral object file format which makes the compiled code to be
executable on many processors
 Platform independent
 Portable
 Java promise: “Write once, run everywhere”.
 Secure
 Robust: measures how well the program runs under various
conditions.
 Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime
checking through mechanisms like exception handling.
14
Java Features(cont’d)
 Multithreaded:
 With Java's multithreaded feature it is possible to write programs
that can do many tasks simultaneously.
 Java differs from other programming languages in that it is both
compiled and interpreted language.
 High Performance: With the use of Just-In-Time compilers,
Java enables high performance.

15
Syntax & Semantics
The syntax rules of a language define how we can put
together symbols, reserved words, and identifiers to
make a valid program
The semantics of a program statement define what
that statement means (its purpose or role in a
program)
A program that is syntactically correct is not
necessarily logically (semantically) correct
A program will always do what we tell it to do, not
what we meant to tell it to do

16
Errors
A program can have three types of errors

The compiler will find syntax errors and other basic


problems (compile-time errors)
 If compile-time errors exist, an executable version of the
program is not created

A problem can occur during program execution, such


as trying to divide by zero, which causes a program to
terminate abnormally (run-time errors)

A program may run, but produce incorrect results,


perhaps using an incorrect formula (logical errors)

17
Java Program Structure
In the Java programming language:
 A program is made up of one or more classes
 A class contains one or more methods
 A method contains program statements

A Java application always contains a method called


main

18
Java Program Structure(cont’d)

// comments about the class


public class MyProgram
{
class header

class body

Comments can be placed anywhere

19
Java Program Structure(cont’d)

// comments about the class


public class MyProgram
{
// comments about the method
public static void main (String[] args)
{
method body method header

20
First Java Program
A simple code that would print the words Hello World.
public class MyFirstJavaProgram {
public static void main(String[ ] args) {
System.out.println("Hello World");
}
}

21
Basic Syntax
About Java programs, it is very important to keep in
mind the following points.
 Case Sensitivity, E.g. Hello is different from hello
 Class Names - For all class names the first letter shall be in
Upper Case. If several words are used to form a name of the
class, each inner word's first letter should be in Upper Case.
 Example class MyFirstJavaClass
 Method Names - All method names shall start with a lower
case letter. If several words are used to form the name of the
method, then each inner word's first letter should be in Upper
Case. Example public void myMethodName()
 Program File Name - Name of the program file should
exactly match the class name. Example : Assume
'MyFirstJavaProgram' is the class name. Then the file should be
saved as 'MyFirstJavaProgram.java'.
 Public static void main(String[] args)- Java program processing
22
starts from the main()
Java Keywords
The following list shows the reserved words in Java.
These reserved words may not be used as constant
or variable or any other identifier names.

23
Java Identifiers
Names used for classes, variables and methods are
called identifiers.
 All identifiers should begin with a letter (A to Z or a to z),
currency character ($)
or an underscore (_).
 After the first character identifiers can have any combination of
letters, digit, $, and _.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value
 Examples of illegal identifiers: 123abc, -salary

24
Comments in Java
E.g.
public static void main(String []args){
// This is an example of single line comment
/* This is also an example of
multline comment. */
System.out.println("Hello World");
}
}

25
Variable
 A variable is a name for a location in memory
 You must declare all variables before they can be used. The
basic form of a variable declaration is:
 data type variable [ = value][, variable [= value] ...] ;
data type variable name

int total;
E.g. int a, b, c; // Declares three ints, a, b, and c.
 int a = 10, b = 10; // Example of initialization
 byte B = 22; // initializes a byte type variable B.
 double pi = 3.14159; // declares and assigns a value of PI.
 char a = 'a'; // the char variable a iis initialized with value ‘a’

26
Java Variable Types(cont’d)
 There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types

Data Size Range


Type
byte 1 byte Integers in the range of -128 to +128
short 2 bytes Integers in the range of -32,768 to +32,767
int 4 bytes Integers in the range of -2,147,483,648 to
+2,147,483,647
long 8 bytes Integers in the range of -9,223,372,036,854,775,808
to +9,223,372,036,854,775,807
float 4 bytes Floating-point numbers in the range of ±3.4x10-38 to
±3.4x1038 with 7 digits of accuracy
double 8 bytes Floating-point numbers in the range of ±1.7x10-308 to
±1.7x10308 with 15 digits of accuracy

27
Constants
A constant is an identifier that is similar to a variable
except that it holds the same value during its entire
existence
Example:
 byte a = 68;
 char a = 'A'

In Java, we use the final modifier to declare a


constant final int MIN_HEIGHT = 69;

28
The println Method
We can invoke the println method to print a
character string
The System.out object represents a destination (the
monitor screen) to which we can send output

System.out.println ("Whatever you are, be a good one.");

object method
information provided to the method
name
(parameters)

29
The print Method
The System.out object provides another service as
well

The print method is similar to the println method,


except that it does not advance to the next line

Therefore anything printed after a print statement


will appear on the same line

30
Escape Sequence(cont’d)
What if we wanted to print a the quote character?
The following line would confuse the compiler
because it would interpret the second quote as the
end of the string
System.out.println ("I said "Hello" to you.");

An escape sequence is a series of characters that


represents a special character
An escape sequence begins with a backslash
character (\)

System.out.println ("I said \"Hello\" to you.");

31
Escape Sequence

32
EscapeExample.java
public class EscapeExample{
public static void main( String args[] ){
System.out.println("Hello World");
System.out.println("two\nlines");
System.out.println("\"This is in quotes\"");
}
}
Output:
Hello World
two
lines
“This is in quotes”

33
String
 A string of characters can be represented as a string literal by
putting double quotes around the text:
 Examples:
"This is a string literal."
"123 Main Street"
 There are close to 50 methods defined in the String class. We
will introduce some of them here:
 substring
 E.g. String text;
text = "Espresso";
System.out.print(text.substring(2, 7));
 Output: press
 Length
 Example
 text1 = ""; //empty string
 text2 = "Hello";
 text3 = "Java";
 text1.length( ) //output: 0
 text2.length( ) //output: 5
 text3.length( ) //output: 4 34
String(cont’d)
Indexof()
 To locate the index position of a substring within another string, we
use the indexOf() method
 Example
 text = "I Love Java and Java loves me.";
 text.indexOf("J") =7
 text.indexOf("love") =21
 text.indexOf("ove") =3

String concatenation
 We can create a new string from two strings by concatenating the
two strings. We use the plus symbol (+) for string concatenation
 string text1 = "Jon";
 string text2 = "Java";
 text1 + text2--------- "JonJava"
 text1 + " " + text2--------- "Jon Java"
 "How are you, " + text1 + "?"-------------- "How are you, Jon?"
35
StringExample.java
public class StringExample{
public static void main(String[] args) {
String text1="Espresslo", text2 = "Hello“;
String text3 = "I Love Java and Java loves me.";
System.out.println(text1.substring(2,7));
System.out.println(text2.length());
System.out.println(text3.indexOf("I"));
System.out.println(text1+" "+text2);
}
}
Output:?

36
Simple Type Conversion/Casting
A value in any of the built-in types we have seen so
far can be converted (type-cast) to any of the other
types.
 For example: (int) 3.14 // converts 3.14 to an int 3
 (double) 2 // converts 2 to a double to give 2.0
 (string) 122 // converts 122 to a string whose
code=122
 Integer division always results in an integer outcome.
 Division of integer by integer will not round off to the next
integer
 E.g.: 9/2 gives 4 not 4.5
 E.g 8.2/2=4.1 implicit conversion/promotion

37
Java Basic Operators
Java provides a rich set of operators to manipulate
variables. We can divide all the Java operators into
the following groups:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Assignment Operators

38
Arithmetic Operator

39
Example
public class Test{
public static void main(String args[]){
int a =10;
int b =20;
int c =25;
int d =25;
System.out.println("a + b = "+(a + b));
System.out.println("a - b = "+(a - b));
System.out.println("a * b = "+(a * b));
System.out.println("b / a = "+(b / a));
System.out.println("b % a = "+(b % a));
System.out.println("c % a = "+(c % a));
System.out.println("a++ = "+(a++));
40
Example(cont’d)
System.out.println(“a-- = "+(a--));
// Check the difference in d++ and ++d
System.out.println("d++ = "+(d++));
System.out.println("++d = "+(++d));
}
}
This would produce the following result:
 a + b =30
 a - b =-10
 a * b =200
 b / a =2
 b % a =0
 c % a =5
 a++=10
 b--=11
 d++=25
 ++d =27
41
The Relational Operator

42
Example
public class Test{
public static void main(String args[]){
int a =10;
int b =20;
System.out.println("a == b = "+(a == b));
System.out.println("a != b = "+(a != b));
}
}

This would produce the following result:


 a == b =false
 a != b =true

43
The Logical Operators

44
Example
public class Test{
public static void main(String args[]){
boolean a =true;
boolean b =false;
System.out.println("a && b = "+(a&&b));
System.out.println("a || b = "+(a||b));
System.out.println("!(a && b) = "+!(a && b));
}
}

This would produce the following result:


 a && b =false
 a || b =true
 !(a && b)=true
45
The Assignment Operator

46
Basic Classes
1. System: one of the core classes
 System.out.println( "Welcome to Java!" );
 System.out.print(“…”);
 System.exit(0);

47
Basic Classes(cont’d)
2. Scanner:
 The java.util.Scanner: for accepting input from console
 Methods: nextInt(), nextDouble(), nextLine(), next(), …
 Eg:- Scanner s=new Scanner (System.in);
int x=s.nextInt();
3. JOptionPane
 The JOptionPane provides dialog boxes for both input and
output.

48
Basic Classes(cont’d)
Eg:
 int x =JOptionPane.showInputDialog( "Enter first integer" );
 JOptionPane.showMessageDialog( null, “result" + sum, “Title",
PLAIN_MESSAGE);
 The following statement must be before the program’s class
header(tells the compiler where to find the JOptionPane class)
import javax.swing.JOptionPane;

49
Example 1
import java.util.Scanner; // so that I can use Scanner
public class Age{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? "); // prompt
int age = console.nextInt();
System.out.println("You'll be 30 in " + (30 - age) + " years.");
}
}
Output:
How old are you? 18
You’ll be 30 in 12 years

50
Example 2
import java.util.*;
public class HelloName{
public static void main(String args[]){
Scanner input= new Scanner(System.in);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hello there " + name + ", nice to meet you!");
}
}
Output:
What is your name? Leta
Hello there Leta, nice to meet you! 51
Example3
import java.util.Scanner; // program uses class Scanner
// Addition program that displays the sum of two numbers.
public class AdditionExample{
// main method begins execution of Java application
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2
System.out.print( "Enter first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
sum = number1 + number2; // add numbers
System.out.println( "Sum is “ + sum );
} // end method main
} // end class Addition

52
Example 4
import javax.swing.JOptionPane;
String firstNumber, secondNumber;
int number1,number2,sum;
firstNumber =JOptionPane.showInputDialog( "Enter first
integer" );
secondNumber = JOptionPane.showInputDialog( "Enter second
integer" );
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
sum = number1 + number2;

JOptionPane.showMessageDialog( null, "The sum is " + sum,


"Results", JOptionPane.PLAIN_MESSAGE );
System.exit( 0 );

53
Basic Classes(cont’d)
4. Math-Class
The java.lang.Math class contains methods for
performing basic numeric operations such as the
elementary exponential, logarithm, square root,
and trigonometric functions
 Eg: Math.ceil(x)
 Math.floor(x)
 Math.PI;
 Math.sin(x);
 Math.pow(x,y), Math.round(x)
 Math.max(x,y) ,Math.toDegrees(x);
 Math.random(): a random floating point number between 0
and 1. generates a double value in the range [0,1)
 Eg: Math.random()*100 54
Basic Classes(cont’d)
Random is a class used to generate random numbers
between the given lists/ranges.
Example:
import java.util.Random;
import java.util.Scanner;
public class RandomExample {
public static void main(String[] args) {
double x []=new double[20];
Random r=new Random();
int sum=0;
Scanner s=new Scanner(System.in);
for(int i=0;i<5;i++)
{x[i]=r.nextInt(100);
System.out.println(x[i]);
}
} 55
Conditional Statements
Two types:
 If statements
 Switch statements

Syntax of if statements
if(expression){
//Statements will execute if the expression is true
}

56
Example
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}

Output
This is if statement

57
if…else statement
An if statement can be followed by an optional else
statement, which executes when the expression is
false.
if(expression){
//Executes when the expression is true
}else{
//Executes when the expression is false
}

58
Example 1
public class Test2 {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
Output:
This is else statement

59
Example2
public class Test3 {
public static void main(String args[]){
int x = 30;
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
60
Switch
Handles multiple conditions efficiently.
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}

61
Example
public class SwitchTest {
public static void main(String args[]){
char grade = 'C';
switch(grade){
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Well done");
break;
case 'C' :
System.out.println("You passed");
break;
case 'D' :
System.out.println("You Failed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}System.out.println("Your grade is " + grade); 62
Loop
There may be a situation when we need to execute a
block of code several number of times, and is often
referred to as a loop.
You can use one of the following three loops:
 while Loop
 for Loop
 do...while Loop

63
Example
Displaying all squares of numbers 1 to 10
public static void main(String args[]) {
int i=1;
while(i<=10){
System.out.println(i*i);
i++;
}
}

64
Exercise
Write a program to:
1. Check whether a number is even or not…using if &
Scanner
2. Display sum of the first 100 integer numbers using
for loop.

65
Arrays
stores a fixed-size sequential collection of elements
of the same type.
Sysntax:
Data type arrayname[]=new dataType[size];

int x[]=new int[20];


Example-
import java.util.*;
public class ArrayExample{
public static void main(String[] args) {
int x []=new int[20];//array declaration
int sum=0; 66
Scanner s=new Scanner(System.in);
System.out.println("enter the numbers");
for(int i=0;i<5;i++)
{ x[i]=s.nextInt();
sum =sum+x[i];
}
System.out.println("result="+sum);
}}

67
Exercise: Array
1. Write a java program that accepts 5 integers and display
1. the smallest
2. only evens
3. Count only integers>50
2. Insert N-integers from the keyboard and calculate the sum and
average
3. Generate 5 random numbers between 10 and 20 and find the
smallest
4. Generate 5 random numbers between 1 and 50 and find the
largest two
5. Insert a string using Scanner and count the number of ‘a’ in the
string
6. Check if the inserted string is palindrome or not

68

You might also like