4.3 Java
4.3 Java
IB Computer Science
The Koç School
Computer Education Department
JAVA BASICS
Java
Java programming language is the global standard for
developing and delivering embedded and mobile
applications, games, web-based content, and enterprise
software.
Curly braces are used to mark the beginning and end of a class.
The curly braces will always occur in pairs. The open curly brace marks the
beginning of the class and the close curly brace marks the end.
Curly braces are also used to mark other blocks of code within Java programs.
Features of Java
Java is case-sensitive.
All keywords in Java should be declared using lower-case letters.
Classes start with capital letters, methods and variables start with lower case
letters.
Syntax Rules
Method Names − Method names should start with a Lower Case letter. If several words are
used to form the name of the method, each other word's first letter should be in Upper
Case. (public void myMethodName())
Project File Name − Name of the project file should exactly match the class name. When
saving the file, you should save it using the class name (Remember Java is case sensitive)
and append '.java' to the end of the name (if the file name and the class name do not
match, your program will not compile). (Assume 'MyFirstJavaProgram' is the class name.
Then the file should be saved as 'MyFirstJavaProgram.java')
Variable, Constant and Operator
Variable is used to store data elements of a program. The stored data can be
changed during the program execution.
Constant represent things and quantities that don’t change. This can be seen as
non-modifiable variables.
You may ask your Person object, "What is your body mass index (BMI)?”. In
response, Person would use the values of its height and weight attributes to
calculate the BMI.
Or you may want the Person to print all of its attributes.
Benefits of Encapsulation:
• The fields of a class can be made read-only
or write-only.
• A class can have total control over what is
stored in its fields.
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism
Inheritance:
Inheritance can be defined as the process where Super class
one class acquires the properties (methods and
fields) of another. With the use of inheritance, the
information is made manageable in a hierarchical
order.
The class which inherits the properties of other is
known as subclass (derived class, child class) and
the class whose properties are inherited is known
as superclass (base class, parent class). Sub-class
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism
Overriding:
Overriding is a feature that allows a subclass or
child class to provide a specific implementation of a
method that is already provided by one of its super-
classes or parent classes. When a method in a
subclass has the same name, same parameters or
signature and same return type (or sub-type) as a
method in its super-class, then the method in the
subclass is said to override the method in the
super-class.
Principles of OOP: Encapsulation,
Inheritance, Overriding, Polymorphism
Polymorphism:
Polymorphism is the capability of a method to do different things based on the
object that it is acting upon. In other words, polymorphism allows you define one
method and have multiple implementations according to the situation.
VARIABLES, CONSTANTS
AND DATA TYPES
Variable and Value
int x = 3
Declaring, Assigning, Initializing
Declaring is the process of defining the variable.
int number;
Important!
Floating point values are assumed to be of type double unless you explicitly state
that it is a float type, not a double type. You do that by putting an “f” (float) to the
right of the value.
}
Char
• char data type is a single 16-bit Unicode character
• Minimum value is '\u0000' (or 0)
• Maximum value is '\uffff' (or 65,535 inclusive)
• Char data type is used to store any character
System.out.println();
System.out.println("The high temperature today is " +
temperature);
Concatenation Operator
In Java, the plus sign (+) is used to label the data within a println statement. When
the plus sign is used in this context it is referred to as the concatenation operator.
Let's look at some examples.
int testGrade = 87; Test grade = 87
You can bench press 195 pounds.
int weight = 195; The cost of the shirt is 29.95
double cost = 29.95;
System.out.println(a);
System.out.println(f);
}}
Narrowing (Typecasting)
class Simple{ Output:
public static void main(String[] args){
10.5
float f=10.5f;
//int a=f; // compile time error 10
int a=(int)f; // explicit type casting
System.out.println(f);
System.out.println(a);
}}
Number to String
A number cannot be cast to a String—instead we must convert it with a method like
Integer.toString.
This method returns a String version of the int argument.
System.out.println(max_value); Output:
}}
-2147483648
Underflow Example
class Simple{
public static void main(String[] args){
We can see the upper and lower limit of each data type by looking at the
MAX_VALUE and MIN_VALUE constants in wrapper classes.
Example:
System.out.println(Integer.MAX_VALUE);
System.out.println(Integer.MIN_VALUE);
Scope of Variables
The scope of a variable refers to the section of code where a variable can be
accessed.
Scope starts where the variable is declared.
Scope ends at the termination of the statement block in which the variable was
declared.
There are three types of variables:
• Instance
• Local
• Class
Scope of Variables
• Local variables are declared in a method. Local variables are not visible outside the method.
• Instance variables are declared in a class, but outside a method. Visible in all methods. Can be
used in the entirety of the class. Every object in the class may have a different value of this.
• Class/static variables are declared with the static keyword in a class, but outside a method.
Can be used in the entirety of the class. Every object has the same static value of this.
Constant
There are several values in the real world which will never change.
A square will always have four sides,
PI to three decimal places will always be 3.142,
A day will always have 24 hours.
These values remain constant. When writing a program it makes sense to represent
them in the same way - as values that will not be modified once they have been
assigned to a variable. These variables are known as constants.
OPERATORS, ARITHMETIC AND
LOGICAL OPERATIONS
Arithmetic Operators
An expression is a combination of operators and operands, like a mathematical
expression.
The operands might be numbers, variables, or constants.
Expressions usually do a calculation such as addition or division.
In Java, you can form arithmetic expressions involving addition(+), subtraction(-),
multiplication(*), and division (/) in basically the same way that you would form
them in ordinary arithmetic or algebra.
Arithmetic Operators
int a = 5; a = 2; a = 2;
b = ++a; b = a++;
int b = 3;
is same as: is same as:
int c = a * b++; // c is set to 15 a = a + 1; b = a;
int d = a * ++b; // d is set to 20 b = a; a = a + 1;
Increment and Decrement Operators
int count=15;
int a, b, c, d;
a = count++;
b = count;
c = ++count;
d = count;
System.out.println(a + ", " + b + ", " + c + ", " + d);
Output:
What is the output?
15, 16, 17, 17
The Equality and Relational Operators
The equality and relational operators Operator Description
determine if one operand is greater
than, less than, equal to, or not == equal to
equal to another operand. != not equal to
> greater than
>= greater than or
equal to
< less than
<= less than or equal to
Conditional Operators
The && and || operators perform Conditional-AND and Conditional-OR
operations on two boolean expressions.
Operator Description
&& Conditional-AND
|| Conditional-OR
Conditional Operators
import java.util.Scanner;
The import statement instructs the compiler to give a program access to the
Scanner class. The words java and util in the statement are called packages.
Scanner Class
Once we have imported the Scanner class into our program, we are ready to
instantiate a Scanner object.
The above code creates a Scanner object named keyboard. The name keyboard is
arbitrary, you can name your objects anything you want as long as you follow the
rules for declaring identifiers. It should, however, be a name that actually describes
what the object does.
The System.in you see in the parentheses tells the computer that you want to read
from the standard input device - the keyboard.
Scanner Class Example
// 1. Create a Scanner object
Scanner keyboard = new Scanner( System.in );
// 2. Prompt the user
System.out.print( "Type some data for the program: " );
// 3. Use the Scanner to read a line of text from the user.
String input = keyboard.nextLine(); //nextLine() is used for string entry
// 4. Now, you can do anything with the input string that you need to.
// Like, output it to the user.
System.out.println( "input = " + input );
The nextDouble() method enables users to read decimal values from the keyboard.
double num = keyboard.nextDouble();
The nextLine() method enables users to read string values from the keyboard.
String input = keyboard.nextLine();
The next().charAt(0) method enables users to read the first letter entered.
char letter = keyboard.next().charAt(0);
next().charAt (0) Example
Scanner keyboard = new Scanner(System.in);
char letter;
System.out.println();
System.out.println("The letter entered = " + letter);
keyboard.close();
Enter a letter --> e
if(Boolean_expression) {
// Statements will execute
// if the Boolean expression is true
}
If Statements:
Syntax example:
if( x < 20 ) {
System.out.print("This is an if statement");
}
}
}
If-else Statements:
Syntax:
if(Boolean_expression) {
// Executes when the Boolean
// expression is true
}else {
// Executes when the Boolean
// expression is false
}
If-else Statements:
Exercise:
public class Test {
if( x < 20 ) {
System.out.print("The number is smaller than
20");
}else {
System.out.print("The number is equal to or
greater than 20");
}
}
}
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 a few points to keep in mind.
● An if can have zero or one “else” and it must come after any “else if”.
● 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” will be
tested.
The if...else if...else Statement
Syntax:
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3) {
// Executes when the Boolean expression 3 is true
}else {
// Executes when the none of the above condition is
true.
}
The if...else if...else Statement
Exercise:
public class Test {
public static void main(String args[]) {
int x = 30;
if( x == 10 ) {
System.out.print("Value of X is 10");
}else if( x == 20 ) {
System.out.print("Value of X is 20");
}else if( x == 30 ) {
System.out.print("Value of X is 30");
}else {
System.out.print("This is else statement");
}
}
}
Nested if Statement
Syntax:
if(Boolean_expression 1) {
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2) {
// Executes when the Boolean expression 2 is true
}
}
Nested if Statement
Syntax:
public class Test {
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
Switch Statement
Syntax:
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
}
}
Infinite For Loop
// infinite loop
{
int x = 1;
for ( ; ; )
{
System.out.println(x);
x++;
}
}
Exercise I
Write a Java program to print the following output by using for loop:
Exercise II
Write a program that takes a number “n” from the user. Then prints that many
numbers from 1 to n, side by side (with a space in between each).
Sample Output:
How many numbers do you want to see?
20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
While
If the boolean_expression result is true, then the actions inside
the loop will be executed. This will continue as long as the
expression result is true.
When the condition becomes false, program control passes to
the line immediately following the loop.
Key point of the while loop is that the loop might not ever run.
When the expression is tested and the result is false, the loop
body will be skipped and the first statement after the while loop
will be executed.
Syntax:
while(Boolean_expression) {
// Statements
}
While
public class Test { value of x : 10
value of x : 11
public static void main(String args[]) { value of x : 12
int x = 10; value of x : 13
value of x : 14
value of x : 15
while( x < 20 ) { value of x : 16
System.out.println("value of x : " + x ); value of x : 17
x++; value of x : 18
} value of x : 19
}
}
Infinite While Loop
class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
Exercise
Write a program that calculates the sum and average of grades numbers by the
user until user enters a number less than 0 or more than 100.
Output:
x++;
}while( x < 20 );
}
}
Do … while
while(condition) // no semicolon here
{
....
}
do
{
...
}
while(condition); // a semicolon here
Loop Control Statements:
The break statement in Java programming language
has the following two usages
● When the break statement is encountered inside
a loop, the loop is immediately terminated and
the program control resumes at the next
statement following the loop.
● It can be used to terminate a case in the switch
statement.
Loop Control Statements:
public class Test { 10
20
public static void main(String args[]) {
1. java.util.Random class
2. Math.random method
java.util.Random
For using this class to generate random numbers, we have to first create an
instance of this class and then invoke methods such as nextInt(), nextDouble(),
nextLong() etc using that instance.
We can generate random numbers of types integers, float, double, long,
booleans using this class.
We can pass arguments to the methods for placing an upper bound on the range
of the numbers to be generated. For example, nextInt(6) will generate numbers in
the range 0 to 5 both inclusive.
java.util.Random
import java.util.Random;
public class generateRandom{
public static void main(String args[]) {
Random rand = new Random(); // create instance of Random class
int x = rand.nextInt(1000); // Generate random integer in range
0 to 999
System.out.println("Random Integer: ” + x);
test scores...
test16 = keyboard.nextInt();
test17 = keyboard.nextInt();
test18 = keyboard.nextInt();
test19 = keyboard.nextInt();
test20 = keyboard.nextInt();
Need for Arrays
Array Solution:
Scanner keyboard = new Scanner(System.in);
int[] tests = new int[5]; // declare and initialize an array
int sum = 0, avg = 0;
Array variable(tests) is not the array. It is only the place holder for the array.
In order to create the array itself we must specify its type and how many elements
it is to contain. To declare an array variable you must include square brackets[]
between the data type and variable name.
Defining Arrays:
tests = new int[10]; // Define an array of 10 integers
This statement creates an array that will store 10 values of type int, and records a
reference to the array in the variable tests. The reference is simply where the
array is in memory.
Declaration, Instantiation and Initialization of Array
We can declare, instantiate and initialize the java array together by:
int[] array = {1, 3, 5, 7, 11, 13, 15};
Here is an example of a string array that uses an initializer list to assign values
to each of its elements.
String[] flag = {"red", "white", "blue"};
Common Error:
A common error that programmers make when using arrays is an
IndexOutOfBounds Exception.
This error occurs when you attempt to index an element of an array that does not
exist.
array = new int[3];
After this statement, array[0], array[1], array[2] are possible. array[3] is out of
bound.
Look at the following example.
int[] array = new int[3];
array[3] = 99; // This line causes an
IndexOutOfBounds exception
Example:
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList.
double[] myList = new double[10];
Logical Size & Physical Size
When creating (instantiating) an array we are required to give it a size. This size value
represents the physical size of the array. The physical size is the total number of
elements(cells) in the array.
For example, if you needed an array to store the names of students who showed up
for after school tutorials you might declare an array like the following:
//100 is the physical size of the array
String[] tutorials = new String[100];
Logical Size & Physical Size
// 100 is the physical size of the array
String[] tutorials = new String[100];
// counter - logical size of the array
int numStudents = 0;
The counter variable numStudents job is to keep track of how many students are
added to the array.
This counter variable represents the logical size of the array. The logical size of an
array is the current number of elements in the array that are occupied.
The foreach Loops:
Foreach loop or enhanced for loop enables you to traverse the complete array
sequentially without using an index variable.
public class TestArray {