0% found this document useful (0 votes)
2 views30 pages

Chapter #2 Basics of Java Programming

This document provides an overview of the basics of Java programming, including its object-oriented nature, syntax rules, data types, variables, and operators. It explains key concepts such as classes, methods, identifiers, and control statements like if-else and switch. Additionally, it covers primitive and reference data types, as well as arithmetic, relational, and logical operators used in Java programming.

Uploaded by

samiye379
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

Chapter #2 Basics of Java Programming

This document provides an overview of the basics of Java programming, including its object-oriented nature, syntax rules, data types, variables, and operators. It explains key concepts such as classes, methods, identifiers, and control statements like if-else and switch. Additionally, it covers primitive and reference data types, as well as arithmetic, relational, and logical operators used in Java programming.

Uploaded by

samiye379
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming

Chapter Two
Basics of Java Programming
By: Tizazu B.(Software Engineering)
Introduction
 Java programming language was originally developed by Sun
Microsystems.
 Sun Microsystems has renamed the new J2 versions as Java SE,
Java EE and Java ME, respectively.
 Java is guaranteed to be Write Once, Run Anywhere. Java follows
object oriented programming paradigm.
 Object:- Objects have states and behaviors. Example: A dog
has states-color, name, and breed as well as behaviors -
wagging, barking, and eating. An object is an instance of a
class.
 Class:- A class can be defined as a template/ blue print that
describe the behaviors/states that object of its type support.
 Methods:- A method is basically a behavior. A class can
contain many methods.
 Instant Variables:- Each object has its unique set of instant
variables. An object's state is created by the values assigned
to these instant variables.
Cont’d….
 Case Sensitivity - Java is case sensitive which means
identifier Hello and hello would have different meaning
in Java.
 Class Names - For all class names the first letter should
be in Upper Case. Example class MyFirstJavaClass
 Method Names - All method names should start with a
Lower Case letter.
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 '[Link]'
 public static void main(String args[]) - java program
processing starts from the main() method which is a
mandatory part of every java program.
First Java Program
Let us look at a simple code that would print the words
Hello World.
public class MyFirstJavaProgram{
/* This is my first java program.
public static void main(String []args){
[Link]("Hello World"); // prints Hello
World
}
}
1. What Will be the Output?
2. Write a program that displays your name and
department separately?
Java Identifiers
 All Java components require names. Names used for
classes, variables and methods are called identifiers. In
java there are several points to remember about
identifiers. They are as follows:
 All identifiers should begin with a letter (A to Z or a to z ),
currency character ($) or an underscore (_). It cannot
start with a digit.
 After the first character identifiers can have any
combination of characters.
 A key word cannot be used as an identifier.
 Most importantly identifiers are case sensitive.
o Examples of legal identifiers: age, $salary, _value,
__1_value
o Examples of illegal identifiers: 123abc, -salary
Data Types
Variables are reserved memory locations to store
values.
Based on the data type of a variable, the
operating system allocates memory and decides
what can be stored in the reserved memory.
Therefore, by assigning different data types to
variables, you can store integers, decimals, or
characters in these variables.
There are two data types available in Java:
o Primitive Data Types
o Reference/Object Data Types
1. Primitive Data Type
data Minimum value Maximum value default Description
type
byte -2^7 2^7-1 0 8-bit signed two's complement
integer.
short -2^15 2^15-1 0 16-bit signed two's complement
integer.
int -2^31 2^31-1 0 32-bit signed two's complement
integer.
long -2^63 2^63 -1 0l 64-bit signed two's complement
integer.
float 0.0f 32-bit IEEE 754 floating point.
double 0.0d 64-bit IEEE 754 floating point.
boolean True/false True/fals false Represents one bit of information.
char '\u0000' (or 0). '\uffff' (or 65,535) a single 16-bit Unicode character.

2. Reference Data Type


Reference variables are created using defined constructors of the classes.
Class objects and various types of array variables come under reference
data type.
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared
type or any compatible type.
Example: Animal animal = new Animal("giraffe");
Variables
 Each variable in Java has a specific type,
 Which determines the size and layout of the variable's
memory;
 The range of values that can be stored within that memory;
 The set of operations that can be applied to the variable.
 You must declare all variables before they can be used. The basic
form of a variable declaration is shown here:
data type variable [ = value][, variable [= value] ...] ;
 Following are valid examples of variable declaration and
initialization in Java:
 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 is initialized with value 'a'
Java Keywords
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronize this throw
d
throws transient try void
volatile while
String
 Strings which are widely used in Java
programming are a sequence of characters.
 In the Java programming language, strings are
objects.
 The Java platform provides the String class to
create and manipulate strings.
 The most direct way to create a string is to write:
String greeting ="Hello world!"
Basic Operators
1. Arithmetic Operator
Assume integer variable A holds 10 and variable B holds 20, then:

Operator Description Example

+ Addition - Adds values on either side of the A + B will give 30


operator
- Subtraction - Subtracts right hand operand from A - B will give -10
left hand operand

* Multiplication - Multiplies values on either side A * B will give 200


of the operator
/ Division - Divides left hand operand by right B / A will give 2
hand operand
% Modulus - Divides left hand operand by right B % A will give 0
hand operand and returns remainder

++ Increment - Increase the value of operand by 1 B++ gives 21

-- Decrement - Decrease the value of operand by 1 B-- gives 19

Write a java program that displays the arithmetic equations of


two numbers?
Relational Operators
Operator Description Example

Checks if the values of two operands are equal or not, if (A == B) is not


==
• Write a java program that displays the
yes then condition becomes true. true.

!=arithmetic equations of two numbers?


Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the
(A > B) is not
> value of right operand, if yes then condition becomes
true.
true.
Checks if the value of left operand is less than the value (A < B) is true.
< of right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or (A >= B) is not
>= equal to the value of right operand, if yes then condition true.
becomes true.
Checks if the value of left operand is less than or equal (A <= B) is true.
<= to the value of right operand, if yes then condition
becomes true.
Write a java program that comparing and displays the result of two
numbers?
Logical Operator
Operator Description Example
Called Logical AND operator. If both the operands (A && B) is false.
&& are non-zero then the condition becomes true.
Called Logical OR Operator. If any of the two (A || B) is true.
|| operands are non-zero then the condition becomes
true.
Called Logical NOT Operator. Use to reverses the !(A && B) is true.
! logical state of its operand. If a condition is true
then Logical NOT operator will make false.

Conditional Operator (? : )
Conditional operator is also known as the ternary operator.
This operator consists of three operands and is used to evaluate boolean
expressions.
The goal of the operator is to decide which value should be assigned to the variable.
The operator is written as:
Variable x = (expression) ? value if true : value if false.
a =10;
b =(a ==1)?20:30;
[Link]("Value of b is : "+ b );
Assignment Operator
Operator Description Example
= Simple assignment operator, Assigns values from right C = A + B will assign value of A +
side operands to left side operand B into C
+= Add AND assignment operator, It adds right operand C += A is equivalent to C = C + A
to the left operand and assign the result to left
operand
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C - A
operand from the left operand and assign the result to
left operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C * A
operand with the left operand and assign the result to
left operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalent to C = C / A
with the right operand and assign the result to left
operand
%= Modulus AND assignment operator, It takes modulus C %= A is equivalent to C = C % A
using two operands and assign the result to left
operand
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2


Decision and Repetition Statements
Decision statements
 Java has three types of selection statements.
1. The if statement either performs (selects) an action, if a
condition is true, or skips it, if the condition is false.
2. The if…else statement performs an action if a condition is
true and performs a different action if the condition is false.
3. The switch statement performs one of many different
actions, depending on the value of an expression.
 The if statement is a single-selection statement because it selects
or ignores a single action.
 The if…else statement is called a double-selection statement
because it selects between two different actions.
 The switch statement is called a multiple-selection statement
because it selects among many different actions.
The if Statement
 Programs use selection statements to choose among alternative courses of
action.
 The if statement is a single-entry/single-exit control statement.
 An if statement consists of a Boolean expression followed by one or more
statements.
 The syntax of an if statement is:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
 If the Boolean expression evaluates to true, then the block of code inside the if
statement will be executed. If not, the first set of code after the end of the if
statement(after the closing curly brace) will be executed.
 Example:
public class Test{
public static void main(String args[]){
int x =10;
if( x <20){
[Link]("This is if statement");
} }
}
•This would produce the following result:
•This is if statement
The if...else Statement
 The if single-selection statement performs an indicated action only when the
condition is true; otherwise, the action is skipped.
 The if…else double-selection statement allows you to specify an action to
perform when the condition is true and a different action when the condition is
false.
 An if statement can be followed by an optional else statement, which
executes when the Boolean expression is false.
 The syntax of an if...else is:
if(Boolean_expression){ //Executes when the Boolean expression is
true
}else { //Executes when the Boolean expression is false
}
• Example
int x =30;
if(x <20){
[Link]("This is if statement");
}else{
[Link]("This is else statement");
}
The if...else if...else Statement:
 An if statement can be followed by an optional
else if...else statement, which is very useful to test
various conditions using single if...else if
statement.
 When using if, else if , else statements there are
few points to keep in mind.
 An if can have zero or one else's and it must come
after any else if's.
 An if can have zero to many else if's and they must
come before the else.
 Once an else if succeeds, none of the remaining
else if's or else's will be tested.
Cont’d….
The syntax of an if...else is: Example:
public class Test{
If(expression1) public static void main(String args[]){
{ int x =30;
//Executes expression 1 is true if( x ==10){
[Link]("Value of X is 10");
} }
elseif(expression2) elseif( x ==20)
{ {
[Link]("Value of X is 20");
//Executes expression 2 is true }
} elseif( x ==30)
elseif(expression3) {
[Link]("Value of X is 30");
{ }
//Executes expression 3 is true else
} {
else [Link]("This is else statement"
);
{ }
//Executes when the none of }
the above condition is true. }
}
The switch Statement:
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
case.
The following rules apply to a switch statement:
The variable used in a switch statement can only be a byte, short, int, or char.
You can have any number of case statements within a switch. Each case
is followed by the value to be compared to and a colon.
The value for a case must be the same data type as the variable in the switch
and it must be a constant or a literal.
When the variable being switched on is equal to a case, the statements
following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of
control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at
the end of the switch. The default case can be used for performing a task when
none of the cases is true. No break is needed in the default case.
General Syntax: Example
switch(grade)
switch(expression) {
Case 'A':
{ [Link]("Excellent!");
break;
case value : Case 'B':
[Link](“Very God”);
Break;
//Statements Case 'C':
[Link]("Well done");
break;//optional break;
Case 'D':
case value : [Link]("You passed");
Case 'F':
[Link]("Better try again");
//Statements break;
default:
break;//optional [Link]("Invalid grade");
}
default://Optional [Link]("Your grade is "+ grade);
}
//Statements }

}
Repetition Statements
 A repetition (or looping) statement allows you to specify that a
program should repeat an action while some condition remains
true.
 Java has very flexible three looping mechanisms which are
while, do...while, and for Loops.
1. The while Loop
 A repetition (or looping) statement allows you to specify that a
program should repeat an action while some condition remains
true.
 Syntax:
while(Boolean_expression)
{
//Statements
}
Example
public class WhileLoop {
public static void main(String args[])
{
int x =10;
while( x <15)
{
[Link]("value of x : "+ x );
x++;
[Link]("\n");
}
}
}
2. The do...while Loop
 A do...while loop is similar to a while loop, except that a do...while
loop is guaranteed to execute at least one time.
 The while, the program tests the loop-continuation condition at the
beginning of the loop, before executing the loop’s body; if the
condition is false, the body never executes.
 The do…while statement tests the loop-continuation condition after
executing the loop’s body; therefore, the body always executes at
least once.
 When a do…while statement terminates, execution continues with
the next statement in sequence.
 Syntax:
do
{
//Statements
}while(Boolean_expression);
Example
public class DoWhileLoop {
public static void main(String args[]){
int x =10;
do{
[Link]("value of x : "+ x );
x--;
[Link]("\n");
}while( x >5);
}
}
3. The for Loop
 A for loop is a repetition control structure that allows
you to efficiently write a loop that needs to execute a
specific number of times.
 A for loop is useful when you know how many times a
task is to be repeated.
 The for repetition statement, which specifies the
counter-controlled-repetition details in a single line of
Code.
 Syntax:
for(initialization;Boolean_expression; update)
{
//Statements
}
Example for Multiplication table using for loop
public class ForLoop_Multiplication {
public static void main(String args[]){
for (int x=1; x <= 12; x++)
{
for (int y=1; y <= 12; y++)
[Link]( x*y);
[Link]("\n");
}
}
}
4. The Break Keyword
The break keyword is used to stop the entire loop.
The break keyword must be used inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start
executing the next line of code after the block.
Example:
public class Test{
public static void main(String args[]){
int[] numbers ={10,20,30,40,50};
for(int x : numbers){
if(x ==30){
break;
}
[Link]( x );
[Link]("\n");
}
}
5. The continue Keyword
The continue keyword can be used in any of the loop control structures.
It causes the loop to immediately jump to the next iteration of the loop.
Syntax: continue;
Example:
public class ContinueStatment {
public static void main(String args[]){
int[] numbers ={10,20,30,40,50};
for(int x : numbers){
if( x ==30){
continue;
}
[Link]( x );
[Link]("\n");
}
}
}
Thank You!!!
Stay blessed to next session

You might also like