Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

OOP_Chapter 02 Basic Programming in Java

Uploaded by

muniraneim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

OOP_Chapter 02 Basic Programming in Java

Uploaded by

muniraneim
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Chapter Two

Basics in Java Programming

OOP IN JAVA 1
Basic Programming in Java
Learning Objectives: at the end of the class,
you should be able to:
 Describe Structure of Programming in Java

 Describe Basic Elements of Java

 Describe Variable , Data type and Constant

 Differentiate Character and String

 Describe Operator and operator precedence

 Differentiate Statement and Block in Java

 Describe Type Casting

OOP IN JAVA 2
Basics in Java Programming
Structure of Java Program
[Comments] [Namespaces] [Classes]
[Objects]
[Variables] [Methods]
 Comment: is a piece of descriptive text which
explains some aspect of a program.
 Namespace:- are named program regions used to

limit the scope of variable inside the program.


 Class: is the blue print/template that describes the

behaviors/states that object of its type support .


 Object: the real world entity, those entity can be

consist on state and behaviors.


 Variable is name of reserved area allocated in

memory.
OOP IN JAVA 3
…Con
 A method is a separate piece of code that can be
called by a main program or any other method to
perform some specific function.
Documentation Section Suggested

Optional
Package Statement

Optional
Import Statements

Optional
Interface Statements

Class Definitions Optional

Main Method class


{ Essential
Main Method Definition
}
OOP IN JAVA 4
…Con
 Documentation Section: it is a comment that
beneficial for the programmer because they help them
understand the code.
 Package Statement: it is a group of class that are
defined by a name. Package package_name;
 Import Statement: to use a class of another package ,
then you can do this by importing it directly into your
program. Example: import java.lang.Math;
 Interface Statement: An interface is like a class but
includes a group of method declarations.
 Class Definition: A Java program may contain multiple
class definitions.
 Classes are the primary and essential elements of a
Java program.

OOP IN JAVA 5
…Con
Main Method Class
 Since every Java stand-alone program requires a main

method as its starting point, this class is the essential


part of a Java program.
 A simple Java program may contain only this part.

 The main method creates objects of various classes and

establishes communications between them.


 On reaching the end of main, the program terminates

and control passes back to the operating system.

OOP IN JAVA 6
Simple Java Program
 The simplest way to learn a new language is to write a
few simple example programs and execute them.

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

OOP IN JAVA 7
…Con
 Class Declaration: the first line class. Hello declares a
class, which is an object constructor.
 Class is keyword and declares a new class definition and Hello is
a java identifier that specifies the name of the class to be
defined.
 Opening Brace “{”: every class definition in java begins
with an opening brace and ends with a closing brace “}”.
 The main line: the third line public static void
main(String args[]) defines a method named as main.
 Is the starting point for the interpreter to begin the
execution of the program.
 A java program can have any number of classes but only
one of them must include the main method to initiate the
execution.
 Java applets will not use the main method at all.

OOP IN JAVA 8
…Con
 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.
 All parameters to a method are declared inside a pair of
parenthesis. Here, String args[ ] declares a parameter
named args, which contains array of objects of the class
type String.
 The Output Line: The only executable statement in the
program is System.out.println(“ Hello World);
 This is similar to cout<< “constructor of C++.”;
 The println method is a member of the out object, which
is a static data member of System class.
OOP IN JAVA 9
Basic Elements of Java
 The basic elements of Java are:
Keywords (Reserved Words) Identifiers
Literals Comments
Separator
Keywords
 Keywords are predefined identifiers reserved by Java for

a specific purpose.
 There are 60 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.

OOP IN JAVA 10
Keywords …. Con
 Keywords or Reserved word must be lower case letter
but not Upper Case Letter

OOP IN JAVA 11
Keywords …. Con
Keywor Keys
d
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


OOP IN JAVA 12
Keywords …. Con
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


default default action for a switch statement
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
OOP IN JAVA 13
Keywords …. Con
catch handle an exception
declares a block of code guaranteed to be
finally
executed
class signals the beginning of a class definition
abstract declares that a class or method is abstract
specifies the class which this class is a subclass
extends
of
declares that a class may not be subclassed or
final
that a field or method may not be overridden
implemen declares that this class implements the given
ts interface
permit access to a class or group of classes in a
import
package
instanceo
tests whether an object is an instanceof a class
f
interface signals the beginning of an interface definition
OOP IN JAVA 14
Keywords …. Con
declares that a method is implemented in native
native
code
new allocates a new object
defines the package in which this source code file
package
belongs
declares a method or member variable to be
private
private
declares a class, method or member variable to be
protected
protected
declares a class, method or member variable to be
public
public
return returns a value from a method
declares that a field or a method belongs to a class
static
rather than an 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 OOP IN JAVA 15
Java Identifier
 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…


 Identifiers cannot use white spaces

 Most importantly identifiers are case sensitive.

 Uppercase and lowercase letters are distinct


 They can be of any length

OOP IN JAVA 16
Java Identifier…Con
Examples of legal identifiers: age, $salary, _value,
__1_value, AvgTemp ,a7 etc…
Examples of illegal identifiers: 123abc, -salary
,not/ok ,Yes! etc…
 Which is Valid Identifiers and which is Invalid
Identifiers?
A. First Name B. int C.my*Name D. Total##
E. LastName F. Double G. salary H. my_best

OOP IN JAVA 17
Literals
 Literals 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;

OOP IN JAVA 18
Literals …Con
 Character Literals: represent single Unicode
characters enclosed by single quotes.
 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”;

OOP IN JAVA 19
Java Comments
 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:

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

OOP IN JAVA 20
Java Comments…Con
 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 */
 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 */.

OOP IN JAVA 21
Java Separator
 Are symbols used to indicate where groups of code are
divided and arranged.
 In Java, there are a few characters that are used as
separators.
Symbo Name Purpose
l
() Parent Used to contain lists of parameters in method
hesis definition and invocation.
Also used for defining precedence in
expressions, containing expressions in control
statements, and surrounding cast types.
{} Braces Used to contain the values of automatically
initialized arrays. Also used
to define a block of code, for classes, methods,
and local scopes.
[] Bracke Used to declare array types. Also used when
ts dereferencing array values.
OOP IN JAVA 22
;
Data Types, Variables, and Constants
Variables
 A variable is a container which holds the value while
the java program is executed.
 A variable is an identifier that denotes a storage
location used to store a data value.
 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;
Ex: int x;

OOP IN JAVA 23
Data Types, Variables, and Constants…Con
 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
Types of Variable
 There are three types of variables in java:

 local variable

 instance variable

 Static or Class variable

OOP IN JAVA 24
Types of Variable…Con
 local variable: Variables defined inside methods,
constructors or blocks are called local variables.
 The variable will be declared and initialized within the
method and the variable will be destroyed when the
method has completed.
 Instance variables: Instance variables are variables
within a class but outside any method.
 These variables are instantiated when the class is
loaded. Instance variables can be accessed from
inside any method, constructor or blocks of that
particular class.
 Class variables: Class variables are variables
declared within a class, outside any method, with the
static keyword.

OOP IN JAVA 25
Types of Variable…Con

class variable{
int data=40;//instance variable
static int x=100;//static variable
void method(){
int y=90;//local variable
}
}//end of class

OOP IN JAVA 26
Basic Data Type

 Data types represent the different values to be stored


in the variable.
 Data types specify the size and type of values that can
be stored.
 Every variable in Java has a data type.
 Java data types are of two type:
 Primitive Data Types (also called intrinsic or built-in data
types)
 Non-Primitive data Types (also known as Derived or
reference types)

OOP IN JAVA 27
Basic Data Type…Con

OOP IN JAVA 28
Basic Data Type…Con
 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)

 Reference Data Type: Reference variables are


created using defined constructors of the classes. They
are used to access objects.
 These variables are declared to be of a specific type
that cannot be changed. For example, Employee,
Puppy, etc.
 Class objects and various types of array variables come
under reference data type.

OOP IN JAVA 29
Basic Data Type…Con
Data Type Size Range
boolean 1 byte Take the values true and false
 Summary of Javaonly
Data(0/1).
Types
byte 1 byte -2 to 2 -1
7 7

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”

OOP IN JAVA 30
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; //computer area
System.out.println(“The Area of the Circle: ”+area);
}
}

OOP IN JAVA 31
Java Operators and operator precedence
 Operator in java is a symbol that is used to perform
operations.
 Are symbols that take one or more arguments (operands)
and operates on them to a produce a result.
 Are used to in programs to manipulate data and
variables.
 They usually form a part of mathematical or logical
expressions.
 Expressions can be combinations of variables, primitives
and operators that result in a value.
 There are 8 different groups of operators in Java:
Arithmetic operators, Relational operators, Logical
operators, Assignment operator, Increment/Decrement
operators, Conditional operators, Bitwise operators, and
Special operators

OOP IN JAVA 32
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

OOP IN JAVA 33
Arithmetic Operators
 Arithmetic operators are used in mathematical
expressions in the same way that they are used in
algebra.
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

OOP IN JAVA 34
Relational Operators
 Relational operators compare two values
 Produces a Boolean value (true or false) depending on
the relationship.
 Java supports six relational 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 True if x is less than or equal to y,
x <= y
equal to otherwise false.
Greater than or True if x is greater than or equal to y,
x >= y
equal to 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.

OOP IN JAVA 35
Logical Operators
 Java provides three logical/conditional operators for
combining logical expressions.
 Logical operators evaluate to True or False.

 An expression which combines two or more relational

expressions is termed as a logical expression or a


compound relational expression.
Operato Name Example
r
! Logical !(5 == 5) //
Negation (NOT) gives False
&& Logical AND 5 < 6 && 6 < 6 //
gives False
|| Logical OR 5 < 6 || 6 < 5 //gives
True

OOP IN JAVA 36
Conditional Operators
 The character pair ?: is a ternary operator available in java
 It is used to construct conditional expression of the form:
exp1 ? exp2: exp3;
where exp1, exp2 and exp3 are expressions.
 The operator ?: works as follows:
 exp1 is evaluated first. If it is no zero (true), then the

expression exp2 is evaluated and becomes the value of the


conditional expression. exp3 is evaluated and becomes the
value of the conditional expression if exp1 is false.
Example:
 Given a=10, b=15 the expression
 x=(a>b)? a:b; will assign the value of b to x. i.e. x=b=15;

OOP IN JAVA 37
Increment & Decrement Operators
Operato Use Description
r
++ 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

OOP IN JAVA 38
Increment & Decrement Operators…Con

Example : let x =5
Operato Name Example
r
++ Auto Increment ++x + 10 // gives 16
(prefix)
++ Auto Increment x++ + 10 // gives 15
(postfix)
-- Auto Decrement --x + 10 // gives 14
(prefix)
-- Auto Decrement x-- + 10 // gives 15
(postfix)

OOP IN JAVA 39
Bitwise operators
 One of the unique features of java compared to other
high-level languages is that it allows direct
manipulation of individual bits within a word
 Bitwise operators are used to manipulate data at values
of bit level.
 They are used for testing the bits, or shifting them to
the right or left.
 They may not be applied to float or double data types.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
OOP IN JAVA 40
Special operators
 Java supports some special operators of interest such
as instanceof operator and member selection
operator(.).
 instanceof Operator: is an object reference operator

and returns true if the object on the left-hand side is an


instance of the class given on the right-hand side.
Example:
person instanceof student;
is true if the object person belongs to the class student;
otherwise it is false
 Dot Operator: is used to access the instance

variables and methods of class objects.


Example:
person.age; // Reference to the variable age.
person1.salary(); // Reference to the method salary.
OOP IN JAVA 41
The precedence of the Java operators
 The following table shows the order of precedence
for all Java operators, from highest to lowest.
() []
++ -- !
* / %
+ -
> >= < <=
== !=
&&
||
Example:
c=Math.sqrt((a*a)+(b*b));
if((mark<0) || (mark>100))
if((mark>80) && (mark<100))
OOP IN JAVA 42
String and Character
Characters
 In Java, the data type used to store characters is char.
 Characters in Java are indices into the Unicode
character set. We use primitive data types char.
Example char ch=‘a’
 The Java compiler will also create a Character object for
you under some circumstances.
 For example, if you pass a primitive char into a method that
expects an object, the compiler automatically converts the
char to a Character for you.
 Escape Sequences: A character preceded by a
backslash (\) is an escape sequence and has special
meaning to the compiler.

OOP IN JAVA 43
…Con
Escape Sequence Description
\t Inserts a tab in the text at this point.
\b Inserts a backspace in the text at this point.
\n Inserts a newline in the text at this point.
\r Inserts a carriage return in the text at this point.
\f Inserts a form feed in the text at this point.
\' Inserts a single quote character in the text at this
point.
\“ Inserts a double quote character in the text at this
point.
\\ Inserts a backslash character in the text at this point.

OOP IN JAVA 44
Characters Methods
 isLetter(): Determines whether the specified char
value is a letter.
 isDigit(): Determines whether the specified char value
is a digit.
 isWhitespace(): Determines whether the specified
char value is white space.
 isUpperCase(): Determines whether the specified char
value is uppercase.
 isLowerCase(): Determines whether the specified char
value is lowercase.
 toUpperCase(): Returns the uppercase form of the
specified char value.

OOP IN JAVA 45
…Con
 toLowerCase(): Returns the lowercase form of the
specified char value.
 toString(): Returns a String object representing the
specified character value that is, a one-character string.
Example :
Public class Test{
Public static void main(String [] args){
System.out.println(Character.isLetter(‘a’);
System.out.println(Character.isDigit(7);
System.out.println(Character.isLowerCase(‘a’);
System.out.println(Character.isUpperCase(‘a’);
}
}

OOP IN JAVA 46
Java String
 Strings which are widely used in Java programming are
a sequence of characters.
 In the Java programming language, strings are objects.
 From a day-to-day programming standpoint, one of the
most important of Java’s data types is String.
 String defines and supports character strings.
 The String class has eleven constructors and more than
forty methods for examining individual characters in a
sequence, comparing strings, searching substrings,
obtaining substrings, and creating a copy of a string
with all the characters translated to uppercase or
lowercase.

OOP IN JAVA 47
…Strings Methods
Here is the list of methods supported by String class:
 int length(): Returns the length of this string.

 int compareTo(String anotherString) :Compares two


strings lexicographically.
 String concat(String str) :Concatenates the specified
string to the end of this string.
 char[] toCharArray() : Converts this string to a new

character array.
 String toLowerCase(): Converts all of the characters in
this String to lower case using the rules of the default locale.
 String toLowerCase(Locale locale): Converts all of the

characters in this String to lower case using the rules of the


given Locale.
 String toString(): This object (which is already a string!) is

itself returned.

OOP IN JAVA 48
…Strings Methods
 String toUpperCase(): Converts all of the characters in
this String to upper case using the rules of the default
locale.
 String toUpperCase(Locale locale): Converts all of the
characters in this String to upper case using the rules of
the given Locale.
 The trim(); method removes white spaces at the
beginning and end of a string.
Syntax: public String trim( );
Ex: System.out.println(“ wel-come ”.trim()); //prints wel-
come
The replace(); method replaces all appearances of a given
character with another character.
Syntax: public String replace( ‘ch1’, ’ch2’);
Ex: String str1=“Hello”;
System.out.println(str1.replace(‘l’, ‘m’)); // prints Hemmo
OOP IN JAVA 49
…Con
 comparetTo(); Compares two strings lexicographically.
 The result is a negative integer if the first String is less

than the second string.


Syntax : public int compareTo(String anotherString);
public int compareToIgnoreCase(String str);
Ex:(“hello”.compareTo(“Hello”)==0) ?
System.out.println(“Equla”);:System.out.println(“Not
Equal”); //prints Not Equal
 The concat(); method concatenates the specified
string to the end of this string.
Syntax: public String concat(String str)
Ex: System.out.println("to".concat("get").concat("her“)); // returns
together

OOP IN JAVA 50
…Con
 The substring(); method creates a substring starting
from the specified index (nth character) until the end of
the string or until the specified end index.
Syntax : public String substring(int beginIndex);
public String substring(int beginIndex, int endIndex);
Ex: "smiles".substring(2); //returns "iles“
"smiles".substring(1, 5); //returns "miles”
 The startsWith(); Tests if this string starts with the

specified prefix.
Syntax: public boolean startsWith(String prefix);
Ex: “Figure”.startsWith(“Fig”); // returns true

OOP IN JAVA 51
…Con
 The indexOf(); method returns the position of the first
occurrence of a character in a string either starting
from the beginning of the string or starting from a
specific position.
 public int indexOf(String str); - Returns the index of the
first occurrence of the specified substring within this
string.
 public int indexOf(char ch, int n); - Returns the index of
the first occurrence of the character within this string
starting from the nth position.

OOP IN JAVA 52
…Con
Ex: String str = “How was your day today?”;
str.indexOf(‘t’); // prints 17
str.indexOf(‘y’, 17); // prints 21
str.indexOf(“was”); // Prints 4
str.indexOf("day",10)); //Prints 13
 valueOf(); creates a string object if the parameter or
converts the parameter value to string representation
if the parameter is a variable.
Syntax: public String valueOf(variable);
public String valueOf(variable);
Ex: char x[]={'H','e', 'l', 'l','o'};
System.out.println(String.valueOf(x));//prints Hello
System.out.println(String.valueOf(48.958));//prints
48.958

OOP IN JAVA 53
Java Statements & Blocks
 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 class Block{
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);
}
}
OOP IN JAVA 54
Simple Type Conversion/Casting
 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
}} OOP IN JAVA 55
I/O Statements of Java [Scanner & BufferReader]

//Input Statements(Use Scanner class z


found in import java.util.Scanner x= input.nextInt(); // Obtain user
integer input from keyboard
package)
y= input.nextFloat(); // Obtain user
import java.util.Scanner;
float input from keyboard
public class IO {
z= input.nextDouble(); // Obtain
public static void main(String[] args) { user float input from keyboard
String name; /*Output Statements(Use the
int x; statement System.out.println() &
float y; //Variable declarations System.out.println())*/
double z; System.out.println("Your Name is:
Scanner input = new "+name);
Scanner( System.in ); System.out.println("The Value of x is:
/*Create Scanner in main function to “ +x);
obtain input from command window System.out.println("The Value of y is:
*/ "+y);
System.out.println("Enter Your Name: System.out.println("The Value of z is:
"); //prompt user to enter name "+z);
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 &
OOP IN JAVA 56
…Con
//Input Statements(Use BufferReader System.out.print("Please Enter
class found in import import.java.io Your Name:");
package) name=dataIn.readLine();
import java.io.BufferedReader; System.out.print("Please Enter
import java.io.IOException; Your Age:");
import str=dataIn.readLine(); //to read
java.io.InputStreamReader; an input data
public class age=Integer.parseInt(str);
GetInputFromKeyboard { //convert the given string in to
public static void main( String[] integer
args )throws IOException { //Output Statement (Using
BufferedReader dataIn = new System.out.println())
BufferedReader(new System.out.println("Hello "+
InputStreamReader( System.in) name +"! Your age is: "+age);
); }
String name; }
int age;
String str;

OOP IN JAVA 57
Illustration of Java I/O Statements
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 System.out.println("Student GPA: "+gpa);
// Displaying GPA to Console Screen
}
}

OOP IN JAVA 58
Illustration of System.out.println() & System.out.print()

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

OOP IN JAVA 59
Demonstration of The 4 Arithmetic Operations in Java
import java.util.Scanner; System.out.println(“The Sum
Public classIO { x+y= ”+sum);
Public static void main(String[] System.out.println(“The
args) { Difference x-y= ”+dif);
int x, y, sum, dif, pro, quo; System.out.println(“The Product
Scanner input=new Scanner x*y= ”+pro);
(System.in); //create scanner System.out.println(“The
object input to get input from Quotient x/y= ”+quo);
user } //end of main
System.out.println(“Enter any 2 } //end of class IO
integers: ”);
x=input.nextInt();
y=input.nextInt();
sum=x+y;
dif=x-y;
pro=x*y;
Quo=(double) x/y;

OOP IN JAVA 60
End of Chapter Two!!!
THANK YOU!!!
See You in Next Class
!

OOP IN JAVA 61

You might also like