Chapter 2-BasicsinJavaProgramming_Part 1
Chapter 2-BasicsinJavaProgramming_Part 1
2
History of java
Java is an object-oriented programming
language.
Java was developed by James Gosling and his
team at Sun Microsystems in California. Sun
formally announced Java at an industry
conference in May 1995.
In 1991 Sun funded an internal corporate
research project code-named Green. The
language was based on C and C++ and was
originally intended for writing programs
that control consumer appliances such as
toasters, microwave ovens, and others.
The language was first called Oak, named
after the oak tree outside of Gosling’s
office, but the name was already taken, so
the team renamed it Java. 3
Java Application and Java
Applet
Java can be used to program two types
of programs: Applets and applications.
Applets: are programs called that run
within a Web browser. That is, you need
a Web browser to execute Java applets.
Applets allow more dynamic and flexible
dissemination of information on the
Internet
Java Application: is a complete stand-
alone program that does not require a
Web browser.
A Java application is analogous to a
program we write in other programming
languages. 4
Typical Java Environment
Java programs normally undergo five phases
Edit
Programmer writes program (and stores
program on disk)
Compile
Compiler creates bytecodes from program
Load
Class loader stores bytecodes in memory
Verify
Verifier ensures bytecodes do not violate
security requirements
Execute
Interpreter translates bytecodes into
machine language 5
Cont’d…
Create/Modify Source Code
Result
7
Typical Java
Environment(cont’d)
Phase 1: Creating a Program
Consists of editing a file with an editor
program (editor).
You type a Java program (source code) using the
editor, make any necessary corrections and save
the program.
A file name ending with the .java extension
indicates that the file contains Java source
code
Phase 2: Compiling a Java Program into Bytecodes
Use the command javac (the Java compiler) to
compile a program.
E.g.: To compile a program called
Welcome.java, you would type javac Welcome.java
in the command window of your system
8
Typical Java
Environment(cont’d)
If the program compiles, the compiler
produces a .class file called
Welcome.class that contains the compiled
version of the program.
The Java compiler translates Java source
code into bytecodes that represent the
tasks to execute in the execution phase
(Phase 5).
Byte codes are executed by the Java
Virtual Machine (JVM).
Virtual machine (VM) is a software
application that simulates a computer,
but hides the under-lying operating
system and hardware from the programs
that interact with the VM. 9
Typical Java
Environment(cont’d)
Java’s bytecodes are portable. Unlike
machine language, which is dependent on
specific computer hardware, bytecodes
are platform-independent instructions.
That is why Java is guaranteed to be
Write Once, Run Anywhere.
The JVM is invoked by the java command.
For example, to execute a Java
application called Welcome, you would
type the command java Welcome in a
command window to invoke the JVM, which
would then initiate the steps necessary
to execute the application. This begins
Phase 3. 10
Typical Java
Environment(cont’d)
Phase3: loading: placing the program
in memory before executing it.
The class loader takes the .class files
containing the program’s bytecodes and transfers
them to primary memory.
The .class files can be loaded from a disk on
your system or over a network (e.g., your local
college or company network, or the Internet).
Phase 4: Bytecode Verification
bytecode verifier examines their bytecodes to ensure
that they are valid and do not violate Java’s
security restrictions.
Java enforces strong security, to make sure that
Java programs arriving over the network do not
damage your files or your system (as computer
viruses and worms might).
11
Typical Java
Environment(cont’d)
Phase 5: Execution
The JVM executes the program’s bytecodes, thus
performing the actions specified by the program.
In early Java versions, the JVM would interpret
and execute one bytecode at a time; Java
programs execute slowly.
Today’s JVMs typically execute bytecodes using a
combination of interpretation and so-called
just-in-time (JIT) compilation.
The JVM analyzes the bytecodes as they are
interpreted, searching for hot spots—parts of the
bytecodes that execute frequently.
Integrated development environment
(IDE) combines these steps into a
single task.
A graphical user interface is available for editing,
compiling, linking, and running the application.
Example: NetBeans, IntelliJ, Eclipse, Jbuilder, etc. 12
Activity
Describe:
Compile time error
Run-time error
Logical error
What is Java bytecode?
13
Java Features
Object Oriented
Simple
Java is partially modeled on C++, but
greatly simplified and improved
Architectural-neutral: Java compiler
generates an architecture-neutral object file
format which makes the compiled code to be
executable on many processors
Platform independent
Portable
Java promise: “Write once, run everywhere”.
Multithreaded
possible to write programs that can do many
tasks simultaneously.
14
Java Features(cont’d)
Robust: measures how well the program runs
under various conditions.
Java compilers can detect many problems that
would first show up at execution time in other
languages.
Java has a runtime exception-handling feature
to provide programming support for robustness.
Distributed:
Java applications can open and access objects
across the Net via URLs with the same ease as
when accessing a local file system.
Both compiled and interpreted language:
High Performance: With the use of Just-In-
Time compilers, Java enables high performance.
Secure:
15
Java Program Structure
In the Java programming language
A program is made up of one or more
classes
A class contains one or more methods
A method contains program statements
A Java application always contains a
method called main
Java program processing starts from
the main()
16
Java Program
Structure(cont’d)
17
Java Program
Structure(cont’d)
18
First Java Program
A simple code that would print
the words Hello World.
public class MyFirstJavaProgram
{
public static void main(String[]
args)
{
System.out.println("Hello World");
}
}
19
Class Names and Identifiers
Java is a case sensitive E.g. Hello is different from
hello
Class Names - For all class names the first letter
shall be in Upper Case. If several words are used to
form a name of the class, each inner word's first letter
should be in Upper Case.
Example class MyFirstJavaClass
Method Names - All method names shall start with a
lower-case letter. If several words are used to form the
name of the method, then each inner word's first letter
should be in Upper Case.
Example: public void myMethodName()
Program File Name - Name of the program file should
exactly match the class name.
Example: Assume 'MyFirstJavaProgram' is the class
name. Then the file should be saved as
'MyFirstJavaProgram.java'.
20
Cont’d
Names used for classes, variables and
methods are called identifiers.
All identifiers should begin with a letter (A
to Z or a to z), currency character ($) or an
underscore (_).
After the first character identifiers can
have any combination of letters, digit, $,
and _.
A key word cannot be used as an identifier.
Identifiers are case sensitive.
Examples of legal identifiers: age, $salary,
_value, __1_value
Examples of illegal identifiers: 123abc, -
salary
21
Java Keywords
The following list shows the reserved words
in Java. These reserved words may not be used
as constant or variable or any other
identifier names.
22
Comments in Java
E.g.
public class example
{
public static void main(String []args)
{
//This is an example of single line
comment
/* This is also an example of
multline comment. */
System.out.println("Hello
World");
}
} 23
Java language vocabulary
27
print and println Methods
We can invoke the println method to print a character
string
The System.out object represents a destination (the
monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
object method
information provided to the method
name
(parameters)
31
escapeCharactersInJava.java
Out Put:
Hello World!
Hello
World!
She said, "Java is fun!"
Backslash: \
World!
Backspace: ABD
Unicode: ❤
Null character:
32
String
A string of characters can be represented as a string
literal by putting double quotes around the text:
Examples:
"This is a string literal."
"123 Main Street"
There are close to 50 methods defined in the String
class. We will introduce some of them here:
substring
E.g. String text;
text = "Espresso";
System.out.print(text.substring(2, 7)); //char at end
position is not included
Output: press
length
Example
text1 = ""; //empty string
text2 = "Hello";
text3 = "Java";
text1.length( ) //output: 0
text2.length( ) //output: 5
text3.length( ) //output: 4
33
String(cont’d)
equals
Returns true if the calling object string and the
Other_String are equal. Otherwise, returns false.
Example
String greeting = "Hello";
greeting.equals("Hello") returns true
greeting.equals("hello") returns false
toLowerCase
Convert to lowercase
String greeting = "Hi Daneil!";
greeting.toLowerCase() returns “hi daneil!".
toUpperCase
Convert to uppercase
String greeting = "Hi Daneil!";
greeting.toUpperCase() returns "HI DANEIL!".
34
String(cont’d)
Indexof
Locate the index position of a substring within another
string
Example
text = "I Love Java and Java loves me.";
text.indexOf("J") =7
text.indexOf("love") =21
text.indexOf("ove") =3
String concatenation
Use the plus symbol (+) for string concatenation
string text1 = "Jon";
string text2 = "Java";
text1 + text2--------- "JonJava"
text1 + " " + text2--------- "Jon Java"
"How are you, " + text1 + "?"-------------- "How are you,
Jon?"
35
StringExample.java
public class StringExample
{
public static void main(String[] args)
{
String text1=“Hello", text2 = “World“;
String text3 = "I Love Java and Java loves
me.";
System.out.println(text1.substring(1,3));
System.out.println(text2.length());
System.out.println(text3.indexOf("I"));
System.out.println(text1+" "+text2);
}
}
Output:?
36
Type Conversion/Casting
A value in any of the built-in types we
have seen so far can be converted
(type-cast) to any of the other types.
For example:
37
Java Basic Operators
Java provides a rich set of operators
to manipulate variables. We can divide
all the Java operators into the
following groups:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
38
Arithmetic Operator
Assume variable A holds 10 and variable B holds 20
41
The Relational Operator
Assume variable A holds 10 and variable B holds 20
42
Example
public class Test
{
public static void main(String[] args)
{
int a =10;
int b =20;
System.out.println("a == b = "+(a == b));
System.out.println("a != b = "+(a != b));
}
}
This would produce the following result:
a == b =false
a != b =true 43
The Logical Operators
Assume variable A holds 1 and variable B holds 0
44
Example
public class Test{
public static void main(String[] args)
{
boolean t =true;
boolean f =false;
System.out.println("t&&f="+(t&&f));
System.out.println("t||f="+(t||f));
System.out.println("!(t&&f)="+!(t &&
f));
}
}
This would produce the following result:
t&&f=false
t||f=true
!(t&&f)=true
45
The Assignment Operator
46
Conditional Statements
Two types:
If statements
Switch statements
Syntax of if statements
if(expression)
{
//Statements will execute if the
//expression is true
}
47
Example
public class Test {
public static void main(String[] args)
{
int x = 10;
if( x < 20 )
{
System.out.print("This is if
statement");
}
}
}
Output
This is if statement 48
if…else statement
Anif statement can be followed by an
optional else statement, which executes
when the expression is false.
if(expression)
{
//Executes when the expression is
true
}
else
{
//Executes when the expression is
false
}
49
Example 1
public class Test2
{
public static void main(String[] args){
int x = 30;
if(x<20)
{
System.out.print("This is if statement");
}
else
{
System.out.print("This is else statement");
}
}
}
Output:
This is else statement
50
Example2
public class Test3 {
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");
}
}
} 51
Activity
Write a java program to check whether a number is
even or not
Write a java program that reads two integers and
displays in ascending order.
import java.util.Scanner;
public class TwoSort{
public static void main(String[] args){
Scanner console = new Scanner(System.in);
int a= console.nextInt();
int b = console.nextInt();
if (b < a)
{
int t = a;
a = b;
b = t;
}
System.out.println(a);
System.out.println(b);
} }
52
Exercise
Write a java program that displays
the following picture.
53
Switch
Handles multiple conditions efficiently.
switch(expression)
{
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case
//statements.
default : //Optional
//Statements
}
54
Example
public class SwitchTest {
public static void main(String[] args){
char grade = 'C’;
switch(grade){
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
System.out.println("Well done");
break;
case 'C' :
System.out.println("You passed");
break;
case 'D' :
System.out.println("You Failed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
} System.out.println("Your grade is " + grade);
}
}
55
Loop
There may be a situation when we need to
execute a block of code several number of
times, and is often referred to as a loop.
You can use one of the following three
loops:
while Loop
while (condition) {
statements
}
for Loop
for (initialization; condition; update){
statements
}
do...while Loop
do {
(statements )
} while ( boolean-expression ) ); 56
Example 1
Displayingall squares of numbers 1 to 10
public static void main(String[] args)
{
int i=1;
while(i<=10)
{
System.out.println(i*i);
i++;
}
}
57
Example 2: Nested loop
for (int i = 0; i < 3; i++)
{
for (int j = 2; j < 4; j++)
{
System.out.println (i + “ “ + j);
}
}
58
Exercise
Write a program to display sum of the first 100
integer numbers using for loop.
Write statements that can be used in a Java
program to read two integers and display the
number of integers that lie between them,
including the integers themselves. For example,
four integers are between 3 and 6: 3, 4, 5, and
6.
Write a program that reads an integer value and
prints the sum of all even integers between 2
and the input value, inclusive. Print an error
message if the input value is less than 2.
Write a java program that accepts integer value
from a user and display sum of each digit(E.g.
input: 543, result: 5+4+3=12)
59
Basic Classes
1. System: one of the core classes
System.out.println( "Welcome to
Java!" );
System.out.print(“…”);
System.exit(0);
System.out.println("50 plus 25 is " +
50 + 25);
60
Basic Classes(cont’d)
2. Scanner:
The java.util.Scanner: for accepting input from
console
Methods: nextInt(), nextDouble(), nextLine(),
next(), …
E.g.:- Scanner s = new Scanner (System.in);
int x = s.nextInt();
char y=s.next().charAt(0);
61
Example 1
import java.util.Scanner; // so that I can use Scanner
public class Age{
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("How old are you? "); // prompt
int age = console.nextInt();
System.out.println("You'll be 30 in " + (30 - age) + " years.");
}
}
Output:
How old are you? 18
You’ll be 30 in 12 years
62
Example 2
import java.util.*;
public class HelloName{
public static void main(String[] args){
Scanner input= new Scanner(System.in);
System.out.print("What is your name? ");
String name = input.nextLine();
System.out.println("Hello there " + name + ", nice to meet you!");
}
}
Output:
What is your name? James
Hello there James, nice to meet you!
63
Example3
import java.util.Scanner; // program uses class Scanner
// Addition program that displays the sum of two numbers.
public class AdditionExample{
// main method begins execution of Java application
public static void main( String[] args){
Scanner input = new Scanner( System.in );
int number1; // first number to add
nt number2; // second number to add
int sum; // sum of number1 and number2
System.out.print( "Enter first integer: " ); // prompt
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " ); // prompt
number2 = input.nextInt(); // read second number from user
sum = number1 + number2; // add numbers
System.out.println( "Sum is “ + sum );
} // end method main
} // end class Addition
64
Basic Classes(cont’d)
3. Math-Class
The java.lang.Math class contains methods for performing basic
numeric operations such as exponential, logarithm, square root,
and trigonometric functions
Math.ceil(x) //Math.ceil(3.2) and Math.ceil(3.9) both return 4.0
Math.floor(x) // Math.floor(3.2) and Math.floor(3.9) both return 3.0
Math.pow(x,y) //Math.pow(4,2) returns 16.0
Math.round(x) //Math.round(3.2) returns 3; Math.round(3.6) returns 4
Math.max(x,y) // Math.max(1, 2) returns 2
Math.sqrt(x) // Math.sqrt(4) returns 2.0
Math.random(): a random floating point number between 0 and
1. generates a double value in the range [0,1)
Eg: Math.random()*100
Math.toDegrees(x);
Math.PI
Math.sin(x)
65
Basic Classes(cont’d)
Random is a class used to generate random numbers
between the given lists/ranges.
Example:
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
double x []=new double[20];
Random r=new Random();
Scanner s=new Scanner(System.in);
for(int i=0;i<5;i++){
x[i]=r.nextInt(100);
System.out.println(x[i]);
}
}
}
66
Arrays
Stores a fixed-size sequential collection of elements of the
same type.
The index starts at zero and ends at length-1.
69
Activity
What is wrong with the following?
int[] temp = {7, 2, 1.5, 4};
int[] temp= new int[5];
temp[] = {7, 5, 9};
70
Exercise: Array
1. Write a java program that accepts 5 integers and display
1. the smallest
2. only evens
3. Count only integers>50
2. Insert N-integers from the keyboard and calculate the sum and
average
3. Generate 5 random numbers between 10 and 20 and find the
smallest
4. Generate 5 random numbers between 1 and 50 and find the
largest two
5. Insert a string using Scanner and count the number of ‘a’ in the
string
6. Check if the inserted string is palindrome or not
71
Array Lists
An array list stores a sequence of values whose size can
change.
Array lists can grow and shrink as needed.
The ArrayList class supplies methods for common tasks, such as
inserting and removing elements.
ArrayList class is contained in the java.util package
Declaring Array Lists
ArrayList<Type> names = new ArrayList<Type>();
E.g. The following statement declares an array list of strings:
ArrayList<String> names = new ArrayList<String>();
74
Example
Storing input values
ArrayList<Double> inputs = new ArrayList<>();
while (in.hasNextDouble()){
inputs.add(in.nextDouble());
}
Find the largest element
double largest = values.get(0);
for (int i = 1; i < values.size(); i++){
if (values.get(i) > largest){
largest = values.get(i);
}
}
Print all values, marking the largest
for (double element : values){
System.out.print(element);
if (element == largest){
System.out.print(" <== largest
value");
}
System.out.println();
75
}
Cont’d
Removing Matches
int i = 0;
while (i < words.size()){
String word = words.get(i);
if (word.length() < 4){
words.remove(i);
}
else{
i++;
}
}
76
Lab Exercise
Write a program that reverses the digits of a given
positive integer number entered from the
keyboard(don’t use array).
Write a program that prompts the user to enter a
string and displays the number of vowels and
consonants in the string.
Write a program that determines and print the number
of odd, even, and zero digits in an integer value read
from the keyboard
Write a program that reads a string from the user and
prints it one character per line.
77