Lab Module 1 - Basics of Programming with Java
Java 8 basic features
Simple 01 05 Robust
Object Oriented 02 06 Multithreaded
Platform Independent 03 07 Interpreted and Compiled
Secure 04 08 Portable
Java Basic Input and Output
Java Output
In Java, you can simply use
to send output to standard output (screen).
Here,
• System is a class
• out is a public static field: it accepts output data.
Let's take an example to output a line.
Java Output…
Read about printf method in java
Java Input
• The most common way to take user input in Java is using Scanner class which is part of
[Link] package.
• The scanner class can read input from various sources like console, files or streams. This class
was introduced in Java 5.
• Before that we use BufferedReader class(Introduced in Java 1.1).
Follow these steps to take user input using Scanner class:
• Import the Scanner class using import [Link];
• Create the Scanner object and connect Scanner with [Link] by passing it as an argument
i.e. Scanner scn = new Scanner([Link]);
• Print a message to prompt for user input and you can use the various methods of Scanner class
like nextInt(), nextLine(), next(), nextDouble etc according to your need.
Java Input…
Another method to take user input is using
BufferedReader Class. It is a simple class that is
used to read a sequence of characters. It provides
several methods, including:
• read(): Reads a single character.
• read(char[] cbuf): Reads an array of
characters.
• readLine(): Reads an entire line of text.
To know more about BufferedReader Class, refer –
BufferedReader Class in Java
Variables
Variable types and identifiers
• The Java programming language is a statically typed language, which means that
every variable and every expression has a type that is known at compile time.
• The Java programming language is also a strongly typed language, because types limit
the values that a variable can hold or that an expression can produce, limit the
operations supported on those values, and determine the meaning of the
operations.
• Strong static typing helps detect errors at compile time.
• The types of the Java programming language are divided into two categories:
primitive types and
reference types
Variable types…
• Primitive data types are the basic built-in types used to store simple values.
• The primitive types are the non-numeric type (boolean, char) and the numeric types.
• The numeric types are the integral types byte, short, int, long, and the floating-point
types float and double.
• A reference type is a variable that stores the address (reference) of an object, not the
actual value itself.
• The reference types are class types, interface types, and array types.
• An object is a dynamically created instance of a class type or a dynamically created array.
• All objects, including arrays, support the methods of class Object.
• String literals are represented by String objects
Identifiers
• Identifiers are names given to various program elements such as variables,
methods, classes, packages, and interfaces.
• An identifier is a sequence of one or more characters.
• Rules for Defining Identifiers in Java:
1. The first character must be a valid first character (letter, $, _)
2. Each subsequent character in the sequence must be a valid non-first
character (letter, digit, $, _)
3. No Reserved Keywords: Identifiers cannot be Java reserved keywords
(e.g., class, int, public, static, etc.)
4. No Spaces: Identifiers cannot contain spaces.
5. Case Sensitivity: Java is case-sensitive, so myVariable and MyVariable are
considered different identifiers.
6. Length: There is no strict limit on the length of an identifier, but it
should be meaningful and concise.
Identifiers…
Naming Conventions
Naming Conventions…
Number types, strings, constants
• In Java, number types are categorized into integer types and floating-point types under the
primitive data types.
1. Integer Types: Integer types store whole numbers (without decimals).
Number types…
Number types…
Strings
• 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.
Creating Strings
1st The most direct way to create a string is to write:
String greeting = "Hello world!";
2nd Converting Array of characters into String
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
[Link](helloString);
The last line of this code snippet displays hello.
Strings
String Length:
• Methods used to obtain information about an object are known as accessor methods. One accessor
method that you can use with strings is the length() method, which returns the number of
characters contained in the string object.
String palindrome = "Dot saw I was Tod";
int len = [Link](); //len equals 17
Concatenating Strings:
• The String class includes a method for concatenating two strings:
[Link](string2);
• Strings are more commonly concatenated with the + operator, as in
"Hello," + " world" + "!“
• The + operator is widely used in print statements. For example:
String string1 = "saw I was ";
[Link]("Dot " + string1 + "Tod");
Constants
• A constant is an entity in programming that is immutable. In other words, the value that
cannot be changed.
• Java does not directly support the constants. There is an alternative way to define the
constants in Java by using the non-access modifiers static and final.
• According to the Java naming convention the identifier name must be in capital
letters and underscores between words.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
For example, price is a variable that we want to make constant.
static final double PRICE=432.78;
• In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable
fixed.
Constants…
Exercise 1:
Write a Java program that defines a PI constant and calculates the area of a circle using the
given radius.
Operators
Operators
1. Assignment Operator(=)
– The assignment operator causes the operand on the left side of the assignment
statement to have its value changed to the value on the right side of the statement.
– Example:
» x=12;
» x = y;
» x = y+2;
Operators…
2. Numeric or Arithmetic Operators
– The operators for numeric data types include the standard arithmetic
operators:
Exercise 2
1. Write a Java program that declares two integer variables and performs the basic
arithmetic operations: addition, subtraction, multiplication, division, and [Link]
program should compute the result of each operation using the two variables and
display the results on the screen.
2. Modify the program in Question 1 by creating separate methods (functions) for each
arithmetic operation. Define methods for add, sub, mult, div, and mod that take
two integers as parameters and return the result of the operation. Call these methods
from the main method and display the results on the screen.
Operators…
3. Relational Operators
– Java provides six comparison operators or relational operators.
– The following table shows the equality and relational operators.
Operators…
4. Logical Operators
– The logical operators can be used to create a compound Boolean expression.
– The NOT (! ) operator, which negates true to false and false to true.
– The AND (&&) of two Boolean operands is true if and only if both operands are
true.
– The OR (||) of two Boolean operands is true if at least one of the operands is true.
– The EXCLUSIVE OR (^) of two Boolean operands is true if and only if the two
operands have different Boolean values.
Operators…
5. Augmented Assignment Operators
– The arithmetic operators can be combined with the assignment operator
to form augmented operators.
Operators…
6. Increment and Decrement Operators
– The increment (++) and decrement (– –) operators are for
incrementing and decrementing a variable by 1.
Operators…
7. Evaluating Expressions and Operator Precedence:
– Java expressions are evaluated in the same way as arithmetic
expressions.
– When more than one operator is used in an expression, the following
operator precedence rule is used to determine the order of evaluation.
• Multiplication, division, and remainder operators are applied first. If an expression
contains several multiplication, division, and remainder operators, they are applied
from left to right.
• Addition and subtraction operators are applied last. If an expression contains
several addition and subtraction operators, they are applied from left to right.
Operators…
Example:
Operators…
8. Object Operators:
– The new operator: is used to create an object from a class.
– The instanceof operator: is used to test whether the object is an instance of the
specified type (class).
Example:
Student s = new Student(); //object created using new
Student s = new Student();
if (s instanceof Student) //test whether s is an instance of Student
{
[Link]("s is an instance of Student");
}
Type Conversions/Casting
• Floating-point numbers can be converted into integers using explicit casting.
• Casting is an operation that converts a value of one data type into a value of another data type.
• Casting a type with a small range to a type with a larger range is known as widening a type.
• Casting a type with a large range to a type with a smaller range is known as narrowing a type.
• For example, see the following statement:
– double d = 4.5;
– int i = (int)d; // i becomes 4
– [Link]((int) 1.7); // displays 1.
– [Link]((double) 1 / 2); // displays 0.5
Read (Reference 1)
Chapter 2: Elementary Programming
3: Selections
5: Loops
Control Flow Statements
(Selection, Loops and Jumping)
Control Flow Statements
• The statements inside your source files are generally executed from top to bottom, in the order that they
appear(sequential).
• Control flow statements, however, break up the flow of execution by employing decision making,
looping, and jumping, enabling your program to conditionally execute particular blocks of code.
decision-making(selection) statements
if statements,
two-way if-else statements,
nested if and multi-may if-else statements,
switch statements
the looping(repetitive) statements
for,
while,
do-while,
for-each Loop or enhanced for loop
The jumping statements
break,
continue,
return.
Selection …
1. One -Way if Statements
– An if statement executes the statements if the condition is true
– A one-way if statement executes an action if and only if the condition is
true.
– The syntax for a one-way if statement is:
if (boolean-expression){
statement(s);
}
Selection …
2. Two-Way if-else Statements
– An if-else statement decides which statements to execute based on whether the
condition is true or false.
– The syntax for a two-way if-else statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else{
statement(s)-for-the-false-case;
}
Selection …
3. Nested if and Multi-Way if-else Statements
• An if statement can be inside another if statement to form a nested if statement.
• The nested if statement can be used to implement multiple alternatives.
Example:
– For instance, assigns a letter grade to the variable grade according to the
score, with multiple alternatives.
Selection …
Selection …
4. switch Statements
– A switch statement executes statements based on the value of a variable or
an expression
– Overuse of nested if statements makes a program difficult to read.
– Due to this problem, Java provides a switch statement to simplify
coding for multiple conditions.
Selection …
Syntax:
switch (switch-expression) {
case value1: statement(s)1;
break;
case value2: statement(s)2;
break;
...
case valueN: statement(s)N;
break;
default: statement(s)-for-default;
}
Selection …
• The switch statement observes the following rules:
– The switch-expression must yield a value of char, byte, short, int, or String
type and must always be enclosed in parentheses.
– The value1, . . ., and valueN must have the same data type as the value of
the switch-expression.
• Note that value1, . . ., and valueN are constant expressions, meaning that they
cannot contain variables, such as 1 + x.
Selection …
– When the value in a case statement matches the value of the switch-
expression, the statements starting from this case are executed until either a
break statement or the end of the switch statement is reached.
– The default case, which is optional, can be used to perform actions when none
of the specified cases matches the switch-expression.
– The keyword break is [Link] break statement immediately ends the
switch statement.
Selection …
5. Conditional Expressions
– A conditional expression evaluates an expression based on a condition.
– Syntax: boolean-expression ? expression1 : expression2;
– Example, the following statement assigns 1 to y if x is greater than 0, and -1 to y
if x is less than or equal to 0.
if (x > 0)
y = 1; y = (x > 0) ? 1 : -1;
else
y = -1;
Repetitive /Loops
• A loop can be used to tell a program to execute statements repeatedly.
• Java has four Loop control structures
– The While Loop
– The Do-while Loop
– For Loop
– For each or enhanced for loop
• Nested Loop
Repetitive…
1. The while Loop
– A while loop executes statements repeatedly while the condition is true.
– The syntax for the while loop is:
while (condition) {
Statement(s);
}
Repetitive…
2. The do-while Loop
– A do-while loop is the same as a while loop except that it executes the
loop body first and then checks the loop condition.
– The do-while loop is a variation of the while loop.
– Its syntax is:
do{
Statement(s);
} while(condition);
Repetitive…
3. The for Loop
– A for loop has a concise syntax for writing loops.
– In general, the syntax of a for loop is:
for (initialization; condition; increment) {
Statement(s);
}
Repetitive…
4. for-each Loop or enhanced for loop
– Java supports a convenient for loop, known as a for-each loop, which enables you
to traverse the array sequentially without using an index variable.
– The syntax for a for-each loop is:
for (elementType element: arrayRefVar) {
// Process the element
}
– For example, the following code displays all the elements in the array myList:
double[] myList = {1.5,5.5,3.4,0.5,7.9};
for (double u: myList) {
[Link](u);
}
– You can read the code as “for each element u in myList, do the
following.”
Repetitive…
5. Nested Loops
– A loop can be nested inside another loop.
– Nested loops consist of an outer loop and one or more inner loops.
public class MultiplicationTable {
public static void main(String[] args) {
[Link]("Multiplication Table");
[Link](" ");
for (int j = 1; j <= 9; j++)
[Link](" " + j);
[Link]("\n ----------------------------------------------------------");
for (int i = 1; i <= 9; i++) {
[Link](i + " | ");
for (int j = 1; j <= 9; j++) {
[Link](" " + (i * j));
}
[Link]();
}
}
}
Jumping Statements
– The break and continue keywords provide additional controls in a loop
– Example using Break
Jumping Statements…
Example using continue
Jumping Statements…
• Example using return
• return is used for jumping out of a method.
Arrays
Java Arrays
• An array is a group of variables (called elements or components) containing values that all
have the same type.
• Arrays are objects, so they’re considered reference types.
• Arrays remain the same length once they’re created, although an array variable may be
reassigned such that it refers to a new array of a different length.
Declaring and Creating Arrays:
• Array objects occupy space in memory.
• Like other objects, arrays are created with keyword new.
• To create an array object, you specify the type of the array elements and the number of
elements as part of an array-creation expression that uses keyword new.
E.g.:
Java Arrays…
• It can also be performed in two steps as follows:
• Declaration without Initialization:
int[] numbers; // Preferred way or
int numbers[]; // Also valid but less preferred
• Declaration and Creation (Initialization with Size):
int[] numbers = new int[5]; // Array of 5 integers, initialized to 0 by default
• Declaration, Creation, and Initialization (One-Step Initialization):
int[] numbers = {10, 20, 30, 40, 50}; // Array initialized with specific values
• Separate Declaration and Initialization:
int[] numbers; // Declaration
numbers = new int[3]; // Initialization (size specified)
numbers[0] = 5; // Assigning values
numbers[1] = 10;
numbers[2] = 15;
Java Arrays…
• Access the Elements of an Array:
• We can access array elements using their index, which starts from 0:
numbers[0] = 10; // Setting the first element of the array
int firstElement = numbers[0]; // Accessing the first element
• Change an Array Element:
• To change an element, assign a new value to a specific index :
numbers[0] = 20; // Changing the first element to 20
• Array Length:
• We can get the length of an array using the length property:
// Getting the length of the array
int length = [Link];
Java Arrays…
• Example:
Java Multi-Dimensional Arrays
• A multidimensional array is an array of arrays.
• Multidimensional arrays are useful when you want to store data as a tabular form, like a
table with rows and columns.
• To create a two-dimensional array, add each array within its own set of curly braces:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
Access Elements
• To access the elements of the myNumbers array, specify two indexes: one for the array,
and one for the element inside that [Link] example accesses the third element (2) in
the second array (1) of myNumbers:
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
[Link](myNumbers[1][2]); // Outputs 7
Change Element Values
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers[1][2] = 9;
[Link](myNumbers[1][2]); // Outputs 9 instead of 7
Java Multi-Dimensional Arrays…
Loop Through a Multi-Dimensional Array
• You can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):
Java Arrays Class
• The Java Arrays class (found in [Link]), has methods that allow you to manipulate arrays.
Arrays Methods
• A list of popular methods of the Arrays Class can be found in the table below:
Java Arrays Class…
Java [Link]() Method Java [Link]() Method
Java Arrays Class…
Java [Link]() Java [Link]()
Method Method
Java Arrays…
1. Write a Java program to declare an integer array of size 5, assign values,
and print all elements.
2. Write a program that calculates and prints the sum of all elements in an
integer array.
3. Write a program to copy all elements of an array into another array.
4. Write a Java program that calculates the average of different ages.
5. Merge Array: Write a program that merges two arrays into a single
array.
Java Arrays…
6. Write a Java program to reverse a given array. The program should modify
the array in place and print the reversed result.
7. Write a Java program that checks if a given integer array is a palindrome.
A palindrome is an array that reads the same forward and backward. For
example, {1, 2, 3, 2, 1} is a palindrome because reversing it gives the
same array.
8. Transpose a matrix: Given a 2D array (matrix), transpose it (swap rows
and columns).
Read (Reference 1)
Chapter 7: Single-Dimensional Arrays
8: Multidimensional Arrays