CHAPTER TWO
Basics in Java Programing
Woldia University, Institute of Technology
School of Computing, Department of Computer Science
By: Nega A.
2018 E.C.
1
Chapter Outline
• Introduction to Java • Constants
• Java Identifiers
• Strings
• Data Types
• Arrays
• Variables
• Basic Operators
• Type Conversion/Casting
• Decision Making
• Java Keywords
• Looping Statements
• Comments & Literals
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 2
Learning Objectives
• After completing this chapter, you will be able to:
• Understand Java program structure
• Use identifiers and keywords correctly
• Work with different data types
• Declare and initialize variables
• Perform type casting
• Manipulate strings and arrays
• Use operators effectively
• Implement decision-making statements
• Create loops for repetition
• Writing java Functions
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 3
Java Programming Language
• Historical Background:
• Developed by Sun Microsystems, Initiated by James Gosling (1995)
• Core component of Java platform
• Key Milestones:
• J2 → Renamed to:
• Java SE (Standard Edition)
• Java EE (Enterprise Edition)
• Java ME (Micro Edition)
• Java is
• Guaranteed to be "Write Once, Run Anywhere" (WORA)
• Follows Object-Oriented Programming
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 4
OOP Concepts in Java
• Java language highly support OOP
• Object
• Has states and behaviors
• Example: Dog:- States: color, name, breeze, Behaviors: wagging, barking
• Class
• Template/blueprint for objects that describes behaviors and states
• Defines object structure
• Methods
• Represent behaviors
• Actions an object can perform, Contain program logic
• Instance Variables:- Variables/values that define an object's state
• Declared inside class but outside methods
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 5
First Java Program
public class MyFirstJavaProgram {
• Main() (Fixed): starting point for
/* This is my first java program execution
This will print 'Hello World’ as the output • Static: Called without object
*/ • String [] args: Command Line arguments
public static void main(String[] args) {
// prints Hello World
[Link]("Hello World");
}
}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 6
Java Program Rules and Naming Conventions
• File name: File Extension must be .java
• File name should be exactly similar with public class name
• Case sensitivity:- java is case sensitive
• 'Hello' ≠ 'hello’
• Class names(Nouns) and Interface Names (Adjectives)
• First letter: UPPER CASE
• Inner words: Upper Case
• Example: Class: MyFirstJavaClass, Interface: Runnable
• Method names (Verbs) and Variable Names
• First letter: lower case
• Inner words: Upper Case
• Example: method: myMethodName(), Variable firstName;
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 7
Java identifiers
• Identifiers: Names associated to: Classes, Interfaces, variables, methods, objects, packages
and so on.
• A valid identifier should be
• Begin with: An identifier :
• Letter (A-Z or a-z) • Can not be a keyword/ Reserved word
• Currency character ($) • It is case sensitive
• Underscore (_) • Must be a single word (no space)
• After first character: • Must be declared before use
• Any combination of letters
• Digits (0-9)
• $ or _
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 8
Data Types in Java
1. Primitive Data Types: Predefined by language and named by the keyword
• Stores value directly
• There are eight primitive data types supported by Java.
Examples
data type Minimum value Maximum value default Description • byte b = 100; //100
byte -2^7 2^7-1 0 8-bit signed two's complement integer. • short s = 30000; //3000
short -2^15 2^15-1 0 16-bit signed two's complement
integer.
• int i = 2000; // 2000
int -2^31 2^31-1 0 32-bit signed two's complement
integer.
• long l = 9654320L; // 9654320
long -2^63 2^63 -1 0l 64-bit signed two's complement
integer.
• float price = 19.99f;
float 0.0f 32-bit IEEE 754 floating point. • double d2 = 12.3e-4; // 0.00123
double 0.0d 64-bit IEEE 754 floating point.
• char unicode = '\u0041'; // 'A'
boolean True/false True/fals false Represents one bit of information.
• char ascii = 65; // 'A'
char '\u0000' (or 0). '\uffff' (or 65,535) a single 16-bit Unicode character.
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 9
Data Types in Java
2. Reference/Object Data Types: Created by programmers
• Stores references (memory addresses) to objects
• A reference variable can be used to refer to any object of the declared type or any compatible type.
• Class objects: Student student = new Student();
• String name = "John";
• Arrays
• int[] numbers = new int[5];
• String[] names = {"A", "B", "C"};
• Default value: Default value of any reference variable is null.
• Student s2 = null;
• Variables: Reserved memory locations to store values:- dataType variableName [= value];
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 10
Type conversion/casting
• Casting: Converting one data type to another
• Casting between primitive types most commonly occurs with the numeric types;
• Boolean values cannot be cast to any other primitive type.
• 1. Automatic (Widening)
• byte → short → int → long → float → double
✓ No data loss
✓ Done automatically by Java
2. Explicit (Narrowing): Must use cast operator: (type)
• double → float → long → int
• Possible data loss
• Example : int c; double d = 323.142; c= (int) d
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 11
Java keywords/reserved words
abstract assert boolean break
byte case catch char
class const continue default
do double else enum
• The following list shows the reserved words extends final finally float
in Java. for goto if implements
import instanceof int interface
long native new package
• These reserved words may not be used as
private protected public return
constant or variable or any other identifier short static strictfp super
names. switch synchronized this throw
throws transient try void
volatile while
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 12
Ccomments in Java
• Three types of comments:
1. Single-line comment
// This is a single line comment int x = 10; // comment after code
2. Multi-line comment
/* This is a multi-line
comment spanning multiple lines */
3. Documentation comment (JavaDoc)
/**
* This method calculates sum
Comments improve code readability
* @param a first number
Ignored by Java compiler
* @param b second number
*/
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 13
Java Laterals and constants
Literals: Source code representation of fixed values
Constants
• Literals can be assigned to primitive type variables: • Variables whose values never change
◦ byte a = 68; char a = 'A' • The value of a constant can be assigned
• Java language supports few special escape sequences only once,
• Use 'final' keyword:
for String and char literals. They are: • Example: final String
Notation Character represented
\n Newline
MANUFACTURER=“J.B. Limited”;
\f Formfeed
\b Backspace
\s Space
\t tab
\" Double quote
\' Single quote
\\ backslash
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 14
Java String and its Methods
• String: Sequence of characters
• String is a class, not a primitive type Common String Methods
Method Description
• Three ways to create strings: length() Returns string length
• 1. String literal toLowerCase() Converts to lowercase
• String s1 = "java"; toUpperCase() Converts to uppercase
trim()
• 2. From char array: concat(String)
Removes whitespace
Appends string
• char[] ch = {'s','t','r'}; charAt(int) Returns character at index
• String s2 = new String(ch); substring(strt, end) Substring from string
• 3. Using new keyword replace(‘old’, ‘new’) Replace old str by new
String[] split(String regex)
• String s3 = new String("example"); Splits the string
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 15
Arrays in Java
• Arrays are objects that store multiple variables of the same type.
• The elements of an array can be either primitive types or reference types.
• Array with no name is called an anonymous array performed for instant use
• Array Characteristics
• Homogeneous (same data type) • Last index: length-1
• Fixed size (cannot change after creation) • Random access by index
• Strongly typed • Can be cloned using clone()
• new keyword crucial for creation • Can have anonymous arrays
• Can store primitive and reference
• Index always starts at 0
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 16
Declaring an array
1. Preferred way: dataType[] arrayRefVar;
• double[] myList; // preferred
2. Alternative way (C-style): dataType arrayRefVar[];
• double myList[]; // works but not preferred
3. Declaration + Creation:
• dataType[] arrayRefVar = new dataType[arraySize];
• double[] myList = new double[10];
4. With initial values
• int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 17
Multidimensional Array
• Multidimensional arrays are arrays of arrays
• To declare a multidimensional array variable, specify each additional index using another set of
square brackets
• Example: int twoD[][] = new int[4][5]; //4 row and 5 column
• You can also create a multi-dimensional array with default values by omitting the values in the
initialization statement.
• Example: int[][] matrix = {{1, 2}, {3, 4}, {5, 6}};
Q. Write a Java program that calculate sum of all diagonal elements of 5X5 double
dimensional array. s
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 18
Operators in Java
• Arithmetic Operators • Conditional Operator (? : )
• known as the ternary operator
• Relational Operators • used to evaluate boolean expressions
• is to decide which value should be assigned to the variable
• Bitwise operators • instanceOf Operator
• used only for object reference variables
• Logical Operators • The operator checks whether the object is of a particular
type(class type or interface type).
• Assignment operators • instanceof operator is wriiten as: (Object reference
variable ) instanceof (class/interface type)
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 19
Precedence of Operators
• Operator precedence determines the grouping of terms in an expression.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= Right to left
|=
Comma , Left to right
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 20
Java Statements: Conditional Statements
1. If Statement: if statement is a single-entry/single-exit control statement.
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
2. The if...else Statement: 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
if(Boolean_expression){
//Executes when the Boolean expression is true
}else {
//Executes when the Boolean expression is false
}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 21
Java Statements: Conditional Statements
3. The if...else if...else Statement: An if statement can 4. Nested if...else Statement: if or
be followed by an optional else if...else statement, else if statement inside another if
which is very useful to test various conditions. or else if statement.
if(Boolean_expression1){
if(Boolean_expression1){
//Executes when the Boolean expression 1 is true
//Executes when the Boolean
}elseif(Boolean_expression2){
expression 1 is true
//Executes when the Boolean expression 2 is true if(Boolean_expression2){
}elseif(Boolean_expression3){ //Executes when the Boolean
//Executes when the Boolean expression 3 is true expression 2 is true
}else{ }
//Executes when the none of the above condition is true. }
}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 22
Java Statements: Switch Statements
• 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.
Syntax:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
default: //Optional
//Statements
}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 23
Java Statements: Switch Statements
Rules
• 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
• The variable used in a switch statement can only be a byte, short, int, or char.
• When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
• If no break appears, the flow of control will fall through to subsequent cases until a
break is reached.
• 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.
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 24
Java Statements: Looping Statements
• A repetition (looping) statement allows you to specify that a program should repeat an
action while some condition remains true.
1. while Loop 2. do...while Loop 3. for Loop
Syntax: Syntax: Syntax:
while(Boolean-expression) do { for(initialization; Boolean-expression;
{ //Statements update)
}while(Boolean-expression); {
//Statements
//Statements
} • Guaranteed to execute at least }
• Loop might not ever run one time • A for loop is useful when you know how
many times a task is to be repeated
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 25
Enhanced for loop in Java
• The enhanced for loop was introduced in java 5. This is mainly used for Arrays.
Syntax:
for(declaration : expression) {
//Statements
}
• Declaration: The newly declared block variable, which is of a type compatible with the elements of
the array you are accessing.
• The variable will be available within the for block and its value would be the same as the current array
element.
• Expression: This evaluates to the array you need to loop through. The expression can be an array
variable or method call that returns an array.
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 26
Enhanced for loop in Java
• Example
public class Test{
public static void main(String args[]){
int[] numbers ={10,20,30,40,50};
for(int x : numbers ){
[Link](x);
[Link](",");
}
[Link]("\n");
String[]names ={"James","Larry","Tom","Lacy"};
for(String name : names ){
[Link]( name );
[Link](",");
}}
}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 27
Jumping Statements in Java
• Break Keyword: used to stop the entire loop. • Continue Keyword: can be used in any of the
• The break keyword must be used inside any loop control structures.
loop or a switch statement. • It causes the loop to immediately jump to the
next iteration of the loop.
public class Test{
public class Test{
public static void main(String args[]){ public static void main(String args[]){
int[] numbers ={10,20,30,40,50}; int[] numbers ={10,20,30,40,50};
for(int x : numbers){ for(int x : numbers){
if( x ==30){ if( x ==30){
break; continue;
} }
[Link]( x ); [Link]( x );
[Link]("\n"); [Link]("\n");
}}} }}}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 28
Functions(Methods) in Java
• A method is a block of code that performs a specific task.
• Think of it as a subprogram that acts on data and often returns a result.
• Why Use Methods?
✓Reusability: Write once, use many times
✓Modularity: Break complex problems into smaller pieces
✓Maintainability: Easy to update and debug
✓Abstraction: Hide complex logic from users
accessModifier returnType methodName(parameters) {
// method body
return value; // if returnType is not void
}
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 29
WiT/Computing, Computer Science Object Oriented Programming Prepared By : Nega A. 30