Java Programming
Basics in Java
Programming
Erku K.
DEBRE BERHAN UNIVERSITY
DEBRE BERHAN
Structure of java Program
[Documentation] - suggested
[package statement] - optional
[import statements] - optional
[interface statements] - optional
[class definitions] - optional
[main method class] - Essential
main method class definition
November 24, 2024 Basics in Java Programming 2
Creating, Compiling and Running
a Java Program
Steps to create a java program:
Write a source file and save with “.java” extension.
Compile the source file into a bytecode file using the compiler, javac.
Run the program contained in the bytecode file using the Java
interpreter installed on your computer.
Note:
File name should be the same as the name of the class containing the
main method.
A program can contain one or more class definitions but only one public class
definition. This class is called main-class because it contains the main method
Program can be created in any text editor.
November 24, 2024 Basics in Java Programming 3
Sample code
public class MyFirstJavaProgram {
public static void main(String
[]args) {
System.out.println("Hello World");
}
}
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
Hello World
November 24, 2024 Basics in Java Programming 4
Sample code Cont…
public (access modifier)
Makes the item visible from outside the class.
static
Indicates that the main() method is a class method not an instant
method.
It allows main() to be called without having to instantiate a particular
instance of the class.
November 24, 2024 Basics in Java Programming 5
Lexical Components of Java Program
Java tokens :
Meaningful words and symbols of java programming language.
Java statements :
Combinations of java Token(s).
Java program :
Comments + java statements + white space
November 24, 2024 Basics in Java Programming 6
Java Tokens
Five types of Tokens:
Reserved keywords
Identifiers
Literals
Operators
Separators.
White space is also considered as a token.
November 24, 2024 Basics in Java Programming 7
Reserved words (Keywords)
• abstract float public
Special meaning to the
• boolean for return
compiler. • break if short
Could not be used as • Byte implements static
constant or variable or • case import super
any other • catch instanceof switch
variable/identifier names. • char int synchronized
• class interface this
• continue long throw
• default native throws
• do new transient
• double null try
• else operator void
• extends package volatile
• final private while
• finally protected
November 24, 2024 Basics in Java Programming 8
Identifiers
Programmer defined tokens.
Include names used to identify :
Classes
Methods
Variables
Objects
Packages and
Interfaces.
Java programming language is case sensitive language.
Example: Mathvar, mathVar, MathVar, etc… are different
identifiers/variables.
November 24, 2024 Basics in Java Programming 9
Rules in naming Identifier
Name must begin with
Letters or
Underscore characters ( _ ) or
Any currency symbol (e.g $)
Remaining characters for the name of identifiers could be :
Letters
Digits
Example:
legal identifiers name: age, $salary, _value, __1_value
illegal identifiers: 123abc, -salary
November 24, 2024 Basics in Java Programming 10
Identifiers’ naming conventions
Class names:
Starts with capital letter(Pascal case) and should be inter-capital(Camel
case)
Variable names:
Start with lower case and should be inter-capital(Camel case)
Method names:
Start with lower case and should be inter-capital(Camel case)
Constants:
Often written in all capital and use underscore if you are using more than
one word.
November 24, 2024 Basics in Java Programming 11
Literals
Values to be stored in variables.
Sequence of characters (digits, letters, & other characters).
November 24, 2024 Basics in Java Programming 12
Operators
Symbol that take one or more arguments (operands) and
Operates on them to produce a result. E.g. +, *, -, /, %...
Types of operators:
Arithmetic operators(+, -, /, *)
Logical operators(&&, ||, !)
Relational operators(==, >=, <=, >, < )
Assignment operators(used to assign a value (=) )
Conditional operators(to evaluate expressions)
Increment and decrement operators(++, --)
Ternary operators (? : )
Bit wise operators (&, |)
Special operators([], (),
November 24, 2024 Basics in Java Programming 13
Separators
Symbols used to indicate where groups of codes are divided and
arranged.
Define the shape and function the code.
Name Symbol
Parenthesis ()
braces {}
brackets []
semicolon ;
comma ,
period .
November 24, 2024 Basics in Java Programming 14
Java Comments
Add clarifications to the codes.
Skipped during the compilation.
Start End Purpose
/* */ The enclosed text is treated as a comment.
// no The rest of the line is treated as a comment.
/** */ The enclosed text is treated as a comment by the compiler but is used by
JavaDoc to automatically generate documentation.
November 24, 2024 Basics in Java Programming 15
Java Statements
Terminated using a semi colon.
Forms a complete unit of execution
Categorized as
Guarding statements
are used for safe handling of
code that may cause exceptions
A labeled statement
is any statement that is prefixed
with an identifier.
November 24, 2024 Basics in Java Programming 16
Blocks, Constants, Variables and Data Types
Block - is a group of zero or more statements between a pair of
braces.
Constants - are fixed values (literals to be stored in variables) that
do not change during the execution of a program.
Should be in capital letters
Re-assigning after declaration is illegal
Cannot be declared inside methods
Declared as:
final var_type symbolic_name= value;
Eg: final float PI=3.14;
Variables - are identifiers that denote a storage location to store a
data values.
November 24, 2024 Basics in Java Programming 17
Data types
Identify amount of memory size and kinds of operations
Categorized as
November 24, 2024 Basics in Java Programming 18
Data types Cont…
November 24, 2024 Basics in Java Programming 19
Variable declaration
Tells the compiler what the variable name is.
It specifies what type of data(value) the variable will hold.
The place of declaration in the program decides the scope of the
variable.
Syntax:
data-type variable_name;
data-type variable_name= value;
Example:
int a, b, c; // Declares three ints, a, b, and c.
byte B = 22; // declares and initializes a byte type variable B.
November 24, 2024 Basics in Java Programming 20
special character
November 24, 2024 Basics in Java Programming 21
Scope of variables
Region of a program within which the variable can be referred
Determines when the system creates and destroys memory for the
variable.
Block defines a scope.
Three types of variables:
Instance variables :
created when objects are instantiated.
Class variables:
global to a class and belong to the entire set of objects that the class creates.
declared as “static” data members.
Local variables:
declared and used inside methods/functions.
Lifetime of a variable is confined to its scope.
November 24, 2024 Basics in Java Programming 22
Operators
Performs a function on one, two, or three operands
Unary operator:
Requires one operand
Conditional operator (?:) :
Used to construct conditional expressions
Form:
Expression1 ?Expression2 : Expression3
Example:
variable x = (expression) ? value if true : value if false
November 24, 2024 Basics in Java Programming 23
Operators Cont…
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
Output:
Value of b is : 30
Value of b is : 20
November 24, 2024 Basics in Java Programming 24
Decision Making Statements
Two types:
if statements
switch statements
November 24, 2024 Basics in Java Programming 25
if Statement
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is
true
}
Example:
public class Test { Output:
public static void main(String args[]){ This is if statement
int x = 10;
if( x < 20 ){
System.out.print("This is if statement");
}
}
}
November 24, 2024 Basics in Java Programming 26
if...else Statement
if statement can be followed by an optional else statement
Syntax:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
public class Test {
public static void main(String args[]){
int x = 30; Output:
if( x < 20 ){
This is else statement
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
November 24, 2024 Basics in Java Programming 27
Loop/Iteration
Executes a block of code several times.
Looping mechanisms:
while Loop
do...while Loop
for Loop
November 24, 2024 Basics in Java Programming 28
while Loop
Allows to write a code that repeats certain task number of times.
Syntax:
while(Boolean_expression)
{
//Statements
}
The statement inside the loop repeatedly executed whenever the
boolean_expression result is true.
November 24, 2024 Basics in Java Programming 29
while Loop
public class Test {
public static void main(String args[]) {
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
November 24, 2024 Basics in Java Programming 30
while Loop Cont…
Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
November 24, 2024 Basics in Java Programming 31
do...while
Similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
do
{
//Statements
}while(Boolean_expression);
November 24, 2024 Basics in Java Programming 32
do...while Cont…
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
November 24, 2024 Basics in Java Programming 33
do...while Cont…
Output:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
November 24, 2024 Basics in Java Programming 34
for Loop
Allows to write an efficient code that repeats certain task number of times.
Syntax:
for(initialization; Boolean_expression; update)
{
//Statements
}
Flow control steps:
Initialization step is executed first, and only once.
Next, the Boolean expression is evaluated.
If it is true, the body of the loop is executed.
If not, loop terminated.
If the body is executed, flow of control jumps back up to the update statement.
Then it continues from the expression evaluation again.
November 24, 2024 Basics in Java Programming 35
for Loop Cont…
public class Test {
public static void main(String args[]) {
for(int x = 10; x < 20; x = x+1) {
System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
November 24, 2024 Basics in Java Programming 36
for Loop Cont…
Output
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
November 24, 2024 Basics in Java Programming 37
break Keyword
Used to terminate block of code.
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int i=0; i<5; i++ ) {
if( numbers[i] == 30 ) { Output:
break; 10
20
}
System.out.print( x );
System.out.print("\n");
}
}
}
November 24, 2024 Basics in Java Programming 38
continue Keyword
Used in any of the loop control structures.
Causes the loop to immediately jump to the next iteration of the loop.
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int i=0; i<5; i++ ) { Output:
if( numbers[i] == 30 ) { 10
continue; 20
40
}
50
System.out.print( x );
System.out.print("\n");
}
}
}
November 24, 2024 Basics in Java Programming 39
Array in Java
Array
is an object which contains elements of a similar data type.
a collection of similar type of elements which has contiguous memory location.
Can be single dimensional or multidimensional array
Syntax – declaration
- single dimensional array
• dataType[] arr;
• dataType []arr;
• dataType arr[];
• arrayRefVar=new datatype[size]; // instantiation
• Multidimenstional
• dataType[][] arrayRefVar;
• dataType [][]arrayRefVar;
• dataType arrayRefVar[][];
• dataType []arrayRefVar[];
• int[][]
November arr=new int[3][3];//3 row and 3 Basics
24, 2024 column // instantiation
in Java Programming 40
Array in Java
Example
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
//instead of the above for loop, we can use for each loop
for(data_type variable:array){
//body of the loop
}
November 24, 2024 Basics in Java Programming 41
Array in Java
Passing array to a method
• class Testarray2{
• //creating a method which receives an array as a parameter
• static void min(int arr[]){
• int min=arr[0];
• for(int i=1;i<arr.length;i++)
• if(min>arr[i])
• min=arr[i];
• System.out.println(min);
•}
• public static void main(String args[]){
• int a[]={33,3,4,5};//declaring and initializing an array
• min(a); Or min(new int[]{10,22,44,66}); //passing array to method
• }}
November 24, 2024 Basics in Java Programming 42
Array in Java
• //Java Program to return an array from the method
• class TestReturnArray{
• //creating method which returns an array
• static int[] get(){
• return new int[]{10,30,50,90,60};
•}
• public static void main(String args[]){
• //calling method which returns an array
• int arr[]=get();
• //printing the values of an array
• for(int i=0;i<arr.length;i++)
• System.out.println(arr[i]);
• }}
November 24, 2024 Basics in Java Programming 43
Array in Java
• Two dimensional array
• Addition of 2 Matrices in Java
• class Testarray5{
• public static void main(String args[]){
• //creating two matrices
• int a[][]={{1,3,4},{3,4,5}};
• int b[][]={{1,3,4},{3,4,5}};
• //creating another matrix to store the sum of two matrices
• int c[][]=new int[2][3];
• //adding and printing addition of 2 matrices
• for(int i=0;i<2;i++){
• for(int j=0;j<3;j++){
• c[i][j]=a[i][j]+b[i][j];
• System.out.print(c[i][j]+" ");
• }
• System.out.println();//new line
• }
• }} 24, 2024
November Basics in Java Programming 44
Lab practice
• Decision making statements
• If
• Switch
• Iteration or repetition statements
• For
• While
• Do .. While
• For each
• Jump statements
• Break
• Continue
• Arrays (single dimensional and multidimensional )
• Exception
November 24, 2024 handling(try … catch,Basics
finally , throw….
in Java Programming 45
Any Question??
Thank you.
November 24, 2024 Basics in Java Programming 46