KEMBAR78
Chapter Two | PDF | Variable (Computer Science) | Data Type
0% found this document useful (0 votes)
9 views51 pages

Chapter Two

Uploaded by

nahit533
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)
9 views51 pages

Chapter Two

Uploaded by

nahit533
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
You are on page 1/ 51

Chapter Two

Basics in Java Programming

Compiled By: Nigusu Y. (Nigusu.Yitayal@inu.edu.et )

1 8/5/2025
Outline
o Identifiers

o Keywords
o Input/output
o Variables
o Data Types
o Operators
o Precedence of operators
o Statements and Blocks
o Control structure
2 8/5/2025
Simple Java Program
Step 1 ) Copy the following code into a notepad.

Public class Welcome {


public static void main(String args[])
{
System.out.println(“Welcome to Java program”);
}
}

Step 2 ) Save the file in the directory C:workspace , as Welcome.java


Step 3 ) Open the command prompt Go to Directory C:workspace
Compile the code using command, javac Welcome.java
Step 4) Run the code using command, java Welcome
3 8/5/2025
Con’t
o Class: It is keyword which is used to declare a class
o Public: It is called access modifier or specifier
• It is used to define accessibility of data members (variable and member
function(methods)).
o Static: Used for memory management
• Can be used is variable function and block.
• Static members are belongs to class rather than object(can be called directly by
the class name).
• Static variable function and block will be in the following section.
o Void: there is no value to be returned by the function.
o Main(): The execution of any program starts from the main function.
o String[] args: It is command line argument that you can write anything in place of
args.
o System.out: stands output object
o Print: is a method or function
4 8/5/2025
Con’t
o When you execute the Java Virtual Machine (JVM) with the java command, the
JVM attempts to invoke the main method of the class you specify.

oThe JVM loads the class specified by Class Name and uses that class name to
invoke method main.

oYou can specify an optional list of Strings (separated by spaces) as command-line


arguments that the JVM will pass to your application.

o Why must main be declared static?


o When you execute the Java Virtual Machine (JVM) with the java command, the
JVM attempts to invoke the main method of the class you specify when no
objects of the class have been created.

oDeclaring main as static allows the JVM to invoke main without creating an
5 8/5/2025
instance of the class.
Java Keywords
✓Keywords are predefined identifiers reserved by Java for a specific purpose.
✓These keywords cannot be used as names for a variable, class or method [Identifiers].

6 8/5/2025
Java Identifiers
o Identifiers are tokens that represent names of variables, methods, classes,
packages and interfaces etc.

o Rules for Java identifiers:


• An identifier is a sequence of characters that consists of letters, digits,
underscores (_), and dollar signs ($).

• An identifier must start with a letter, an underscore (_), or a dollar sign ($).
• It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length. 7 8/5/2025
Java Literals
o Literals are tokens that do not change or are constant.
o 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
• 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 of characters enclosed by double quotes.
Example: String str=“Hello World”;

8 8/5/2025
Java Comments
▪ Java comments are notes written to a code for documentation purposes.

▪ Comment texts are not part of the program and compiler ignores executing them.

▪ Java comments add clarity and code understandability.


▪ Java supports three types of comments:
1. C++-Style/Single Line Comments – Starts with //

E.g. // This is a C++ style or single line comments

2. C-Style: Multiline comments – Starts with /* and ends with */

E.g. /* This is an example of a

C-style or multiline comments */

3. Documentation Comments: The documentation comment begins with a /** and ends
with a */.

E.g. /** This is documentation comment */.


9 8/5/2025
Java Output Statements
o System.out.print(): Print the output with the same line
System.out.print(“Hello world ");

System.out.print(“This is my first java program");

o System.out.println(): Print the output with different/new line.


System.out.println(“Hello world ");

System.out.println(“This is my first java program");

10 8/5/2025
Java Input Statements
o Scanner and BufferedReader class are used to accept data from user/keyboard.
o Scanner class
• Java provides various ways to read input from the keyboard, the java.util package
• Reads input from the user and pass the input stream (System.in) in the
constructor of Scanner class.
Scanner in = new Scanner(System.in);

11 8/5/2025
import java.util.Scanner;
public class javaIO
{
public static void main(String[] args) {
String name;
int x;
double y;
Scanner input = new Scanner( System.in ); //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:"); //prompt user to enter values of x & y
x= input.nextInt(); // Obtain user integer input from keyboard
y= input.nextDouble(); // Obtain user double input from keyboard
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);
}
12 8/5/2025
}
o BufferedReader
▪ Reads text from a character-input stream to provide efficient reading of
characters, arrays, and lines.

▪ The underlying stream reader can be any FileReaders or the


InputStreamReader.

▪ It can be used to read data line by line by readLine() method and makes the
performance fast.

▪ BufferedReader class in Java is found in the java.io package.


BufferedReader br= new BufferedReader(new InputStreamReader( System.in) );

13 8/5/2025
//Accepting inputs using BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class javaIO {
public static void main( String[] args )throws IOException
{
String name;
int age;
String str;
BufferedReader br= new BufferedReader(new InputStreamReader( System.in) );
System.out.print("Please Enter Your Name:");
name=br.readLine();
System.out.print("Please Enter Your Age:");
str=br.readLine(); //to read an input data
age=Integer.parseInt(str); //convert the given string int to integer
System.out.println("Hello "+ name +"! Your age is: "+age);
14 8/5/2025
} }
Data Types in java
o Data types specify the different sizes and values that can be stored in the variable.

o There are two types of data types in Java:

 Primitive data types

▪ They are the building blocks of data manipulation and cannot be further divided
into simpler data types.

▪ Example: Boolean, char, byte, short, int, long, float and double.

 Non-primitive data types: they are not predefined.

▪ They are created by the programmer.

▪ Non-primitive data types are also called 'reference variables' or 'object


references' as they reference a memory location where data is stored

▪ Example: Classes, Interfaces, Arrays, string and enum.


15 8/5/2025
Summary of Java Primitive Data Types

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”
16
8/5/2025
Variables
• A variable is an item of data used to store state of objects and variable has a data
type and a name.
• The data type indicates the type of value that the variable can hold and the variable
name must follow rules for identifiers.
▪ Declaring Variables: The variable declaration tells the compiler to allocate appropriate
memory space for the variable based on its data type.

Syntax o declare a variable is as follows.


data type VariableName; Example: int x;
▪ Initializing Variables: [At moment of variable declaration]
int x = 5; // declaring AND assigning (Initialization)
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
17 8/5/2025
Constants
o In Java, a variable declaration can begin with the final keyword.
o 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;
o Example: program to compute area of circle
public class Area_Circle {
public static void main(String args[])
{
final double pi=3.14;
Output
double area;
The Area of the Circle: 78.5
int rad=5;
area=pi*rad*rad; //compute area
System.out.println(“The Area of the Circle: ”+area);
} 18 8/5/2025

}
Java Operators
o An operator is a symbol that operates on one or more arguments to produce a
result.

❖Assignment Operator (=)


▪ The assignment operator is used for storing a value at some memory location
(typically denoted by a variable).

int 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 19
8/5/2025
%= n %= 25 = n % 25
public 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 8/5/2025
}
Arithmetic Operators
o Java arithmetic operators are used to perform addition, subtraction, multiplication
and division.

o 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

8/5/2025
21
Demo. of arithmetic operators
public class ArithmeticOperators

public static void main(String args[]) {


Output
int x=10; The value of z-y is 5
int y=20; The value of x*y is 200
The value of z/y is 0
int z=25; The value of z%y is 5
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 8/5/2025
Relational Operators
o Java has six relational/comparison operators that compare two numbers and
return a Boolean value.
o The relational operators are <, >, <=, >=, ==, and !=.

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 8/5/2025
Relational operators example
puplic 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
System.out.println( “The value of x is equal to y”)
}
24 8/5/2025
}
Logical Operators
o There are three logical/conditional operators for combining logical expressions.
o 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
Example:
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 8/5/2025

}
Logical operators Demonstration 2
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 8/5/2025
} }}
Increment & Decrement Operators
o The auto increment (++) and auto decrement (--) operators provide a convenient
way of, respectively, adding and subtracting 1 from a numeric variable.

o When used in prefix form, the operator is first applied and the outcome is then
used in the expression.

o When used in the postfix form, the expression is evaluated first and then the
operator applied. Example: int k=5;

Operator Name Example

++ Auto Increment (prefix) ++k + 10; // gives 16

++ Auto Increment (postfix) k++ + 10; // gives 15

-- Auto Decrement (prefix) --k + 10; // gives 14

-- Auto Decrement (postfix) k-- + 10 ; // gives 15

27 8/5/2025
Illustration of increment & decrement operators
public class IncDec
{
public static void main(String[] args)
{
int num;
num = 10; // assign 10 to num
System.out.println(num ); // prints 10
System.out.println(++num ); // prints 11 (Prefix)
System.out.println(num ); // prints11
Program Output
System.out.println(num++ ); // prints 11 (Postfix) 10
System.out.println(num ); // prints 12 11
11
}
11
} 12

28 8/5/2025
Precedence of Java operators
o The order in which operators are evaluated in an expression is significant and is
determined by precedence rules.

29 8/5/2025
30 8/5/2025
Example
public class OperatorPrecedence
{
Output
public static void main(String[] args)
a+b/d = 20
{
a+b*d-e/f = 219
int a = 20, b = 10, c = 0;
int d = 20, e = 40, f = 30;
// (* = / = %) > (+ = -) precedence rules
System.out.println("a+b/d = " + (a + b / d));
System.out.println("a+b*d-e/f = "+ (a + b * d - e / f));

}
}
31 8/5/2025
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 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);32 8/5/2025

}
Simple Type Conversion/Casting
o Type casting enables to convert the value of one data from one type to another type.
(int) 3.14; // converts 3.14 to an int 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)
Example
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
} }
33 8/5/2025
Java control statements
oThe statement is the instruction given to the computer that performs specific types of
work. They can make decisions and repetitive tasks.

oThere are different forms of Java statements:


▪ Declaration statements: used for defining/creating variables.
▪ Arithmetic statements: used for arithmetic operation

▪ Control Statements: used to control the sequence of execution of different


statements of the program.

o There are three main categories of control flow statement;


• Selection or Decision Control Statement
• Repetition or Loop Control Statement
• Branching Control Statement
34
Decision Statements
o Decision statements are Java statements that allows to select and execute specific
blocks of code while skipping other sections.

❖ if statement
o The if-statement specifies that a statement (or block of code) will be executed if
and only if a certain boolean statement is true.

o Syntax: if(condition)

statements;

o The first expression is evaluated. If the outcome is true then statement is executed.
Otherwise, nothing happens.

o Example: When dividing two values, we may want to check that the denominator
is nonzero. if(y!=0)
35
div=x/y;
❖ if-else statement

o The if-else statement is used to execute a certain statement if a condition is true,


and a different statement if the condition is false.
o Syntax: if(condition)
statement1;
else
statement2;
o First expression is evaluated. If the outcome is true then statement1 is executed.
Otherwise, statement2 is executed.
Example: if(score>=50) {
System.out.println("Congratulations! U Passed!”; ");
}
else {
System.out.println(”U Failed!”);
System.out.println(”U Must Take This Course Again!”);
36
}
❖ if-else-if statement
oThe statement in the else-clause of an if-else block can be another if-else
structures.
Examplemple:
oSyntax: int time = 22;
if (condition1) if (time < 10)
// block of code {
else if (condition2) System.out.println("Good morning.");
//executed if the condition1 is false }

else { else if (time < 20)


{
// executed if the condition1 &2 is false
System.out.println("Good Afternoon.");
}
else {
System.out.println("Good evening.");

37
}
switch statement
o The switch statement used to select one of many code blocks to be executed.
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed unless the default
statement is executed .

o Syntax:
switch(expression)
{
case label: // code block
break;
case label: // code block
break;
38
default: // code block }
Demonstration of switch statement
int day = 4;
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
Output
break;
Thursday
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
default:
System.out.println("Sunday");
39
}
40
Looping Statements
▪ Looping statements are Java statements that allows to execute specific blocks
of code a number of times.

▪ Entry controlled loop: The loop in which test condition is checked in the
beginning of the loop.

✓Loop does not execute at all if the condition is false.


Example: for loop, while loop

▪ Exit controlled loop: when statements inside the loop body is executed and
then the condition is checked that loop.

✓The loop executes at least once even if the condition is false.


Example: do-while loop.
41
1) while loop statement
• The while statement is one of the looping constructs control statement that
executes a block of code while a condition is true.

• The loop will stop the execution if the testing expression evaluates to false.
• Syntax:
while(Conditions)
{ // code block to be executed
}
• Example: Adding the first 10 natural numbers(1-10)

int i=1,sum=0;
while(i<=10)
sum+=i;
42
i++;
2) do-while Loop statement
• The do-while loop is similar to the while loop, except that the test
condition is performed at the end of the loop instead of at the beginning.

• The do-while loop executes at least once without checking the


condition.

• When the loop condition becomes false, the loop is terminated and
execution continues with the statement immediately following the loop.
• Syntax:
do

//Statement too be executed

while (<loop condition>);

43
Example
public class do_while {
public static void main(String[] args)
{
int i = 10;
do
{
System.out.println("i is " + i);
i++;
}
while (i < 5);
}
}

44
3) for loop statement
✓ The for loop allows execution of the same code a number of times.
✓ Syntax: for (Initialization; Condition; Expression)
{ // code block to be executed
}
• Initialization –is executed (one time) before the execution of the code block.
• Condition -defines the condition for executing the code block.
• Expression - is executed (every time) after the code block has been executed
✓ Example: int i, sum=0; int i;
for (i = 1; i <= n; i++) for ( i = 0; i < 10; i++ )
{ {
sum += i; System.out.print(i)
} }
45
Nested loop statement
oMany applications require nesting of the loop statements, allowing on loop
statement to be surrounded with in another loop statement.

o Nesting can be defined as the method of embedding one control structure with in
another control structure.

o While making control structures to be reside one with in another, the inner and
outer control structures may be of the same type or may not be of same type.

o But, it is essential for us to ensure that one control structure is completely


embedded within another.

46
//Nested loop demo
public class NestedLoop
{
public static void main(String[] args)
{
int i;
int j;
for(i=5;i>=1;i--) Output
55555
{
for(j=1;j<=i;j++) 4444

{ 333

System.out.print(i+ " "); 22


} 1
System.out.println(" ");
}
}
47
}
Branching Statements
o Branching statements allows us to redirect the flow of program execution.
o Java offers three branching statements: break, continue and return.
❖Continue statement
o The continue statement terminates the current iteration of a loop and instead causes to
jump/proceed to the next iteration of the loop.
o Example:
public class Continue {
public static void main(String[] args) {
int i, sum=0;
for ( i = 1; i <= 10; i++ ) { Output
1
if ( i% 2== 0) {
3
continue; } 5
sum+=i; 7
9
System. out.println(i+" ");
The sum is = 25
}
System.out.println("the sum is = "+sum );
}} 48
❖ break statement
• Break causes immediate termination/exit from looping statements entirely.
• Example:
public class Break {
public static void main(String[] args) {
int num;
num = 10;
//loop while i is less than 6
for(int i=num; i >=1; i--) {
if(i<6){
break; // terminate loop if i <6
}
System.out.print(i + " ");
} Output
System.out.println("Aborted!"); 10 9 8 7 6 Aborted!
49
}}
❖return statement
• The return statement is used to exit from the current method.
• The flow of control returns to the statement that follows the original
method call.
• The return statement has two forms: one that returns a value and one that
doesn't.
Syntax: return expression;
• To return a value, simply put the value (or an expression that calculates
the value after the keyword return.
For example:
return sum;
public double Sum(double x, double y) {
return sum = x+y;
}
• When a method is declared void, use the form of return that doesn't
50
return a value.
The demonstration of return statement
public class Power {
private int x; // instance variables
private int y;
public Power(int a, int b) { //A constructor to Initializes instance variable
x=a;
y=b;
}
public double computePower() { //a method to access the data members
double z;
z=Math . pow (x, y);
return z;
}
public static void main(String args[]) {
Power p= new Power(2,3); //Object creation with a parameterized constructor
double result=p. computePower(); //Assign the return value of the function to the variable result
System.out.println("Output :"+result);
} } 51

You might also like