2. 2
About the JAVA Technology
⢠Java technology is both a programming language and
a platform
⢠The Java programming language is a high-level
language that can be characterized by all of the
following
â Simple
â Architecture neutral
â Object oriented
â Portable
3. 3
About the JAVA Technology
⢠In the Java programming language, all source code is
first written in plain text files ending with the .java
extension.
⢠Those source files are then compiled into .class files
by the Java compiler (javac).
⢠A .class file does not contain code that is native to
your processor; it instead contains bytecodes-- the
machine language of the Java Virtual Machine.
4. 4
Concepts of Objects
Name the person(s) who developed Java?
Answer: Java was developed by James
Gosling & Patrick Naughton at Sun
Microsystems, Inc. in 1991.
What was the initial name of Java?
Answer: Java language was initially called
âOakâ and was renamed âJavaâ in 1995.
5. 5
Concepts of Objects
Important features of JAVA.
Java is a platform - independent language
It is highly reliable
It is a distributed language
It is an object oriented language
What kind of files contain Java source code?
Answer: The Java source code is saved in files with
names the end with â.javaâ.
6. 6
Concepts of Objects
What is source code?
Answer: Source code is the plain text that makes up
the part or all of a computer program.
What is bytecode?
Answer: Bytecode is a low-level computer language
translation of Java source code program.
7. 7
About the JAVA Technology
⢠The Java launcher tool (java) then runs your
application with an instance of the Java Virtual
Machine.
9. 9
About the JAVA Technology
⢠Because the Java Virtual Machine is available on
many different operating systems, the same .class
files are capable of running on
â Microsoft Windows,
â the Solaris TM Operating System (Solaris OS),
â Linux, or
â MacOS.
10. 10
1. Concepts of Objects
What is a Java virtual machine?
Answer: A Java virtual machine(JVM) is a software
system that translates and executes Java bytecode.
Name two types of Java programs?
Answer: We can develop two types of Java
programs
1. Stand-alone application
2. Web applets
11. 11
Concepts of Objects
What is an object?
Answer: An object is an identifiable entity with some
characteristics and behavior.
Example:
Object - Person
Variables - First name, Last name, Age, Weight
12. 12
Creating your First Application
⢠Your first application, HelloWorldApp, will simply
display the greeting "Hello world!". To create this
program, you will:
ďˇ Create a source file. A source file contains text,
written in the Java programming language, that you and
other programmers can understand. You can use any
text editor to create and edit source files.
ďˇ Compile the source file into a .class file. The Java
compiler, javac, takes your source file and translates its
text into instructions that the Java Virtual Machine can
understand. The instructions contained within this file
are known as bytecodes.
ďˇ Run the program. The Java launcher (java) uses the
Java Virtual Machine to run your application.
13. 13
Create a Source File
⢠First, start your editor. You can launch the NotePad editor from
the Start menu by selecting Programs > Accessories >
NotePad. In a new document, type in the following code:
⢠/**
⢠* The HelloWorldApp class implements an application that
⢠* simply displays "Hello World!" to the standard output.
⢠*/
⢠class HelloWorldApp {
⢠public static void main(String[] args) {
⢠//Display "Hello World!"
⢠System.out.println("Hello World!");
⢠}
⢠}
⢠You can save the file as HelloWorldApp.java
15. 15
Compile the Source File
⢠Bring up a shell, or "command," window
⢠You can do this from the Start menu by choosing MS-DOS
Prompt (Windows 95/98) or Command Prompt (Windows
NT/XP), or by choosing Run... and then entering cmd
16. 16
Compile and Run
⢠To Compile the Program, execute the compiler, javac,
specifying the name of the source file on the command line
C:> javac HelloWorldApp.java
⢠The java compiler creates a file called HelloWorldApp.class
⢠To run the program, we must use the Java Interpreter called
Java by,
java HelloWorldApp
⢠The output is displayed,
Hello World!
17. 17
Setting up a project
⢠Click on NetBeans icon in your desktop
⢠Choose File > New Project (Ctrl-Shift-N)
⢠Under Categories, select General
⢠Under Projects, select Java Class Library
⢠Click Next
⢠Under Project Name, enter MyProject1
⢠Click Finish
18. 18
Creating a new program
⢠Choose File > New Project
⢠Under Categories, select General
⢠Under Projects, select Java Application
⢠Click Next
⢠Under Project Name, enter Example1
⢠Click Finish
19. 19
Example 1
Type in the following code:
package example1;
public class Main {
/** Creates a new instance of Main */
public Main() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
System.out.println("Hello Java");
}
}
20. 20
Explanation of the program
⢠/** Creates a new instance of Main */
⢠This is a comment
22. 22
Explanation of the program
⢠public static void main(String[ ] args)
{
⢠This line begins the main() method.
23. 23
Explanation of the program
⢠// TODO code application logic here
⢠This is a single line comment.
⢠It begins with // and ends at the end of the
line.
24. 24
Explanation of the program
⢠System.out.println("Hello Java");
⢠This line outputs the string âHello Javaâ
followed by a new line on the screen.
⢠The println() statement ends with a
semicolon.
⢠All statements in Java end with a semicolon.
⢠The first } is the program ends main()
⢠The last } ends the class definition.
25. 25
Compiling and Running
⢠Click on Run in the Menu bar
⢠Select Run File
⢠Click on âRun Main.Javaâ
To save
⢠Press CTRL+S
26. 26
Example 2
package example2;
public static void main(String args[]) {
int num;
num=100;
System.out.println ("This is num: " + num);
num=num * 2;
System.out.print ("The value of num * 2 is ");
System.out.println(num);
}
}
27. 27
Example 3
package example3;
public static void main(String args[]) {
int x,y;
x=10;
y=20;
if (x<y) System.out.println(âx is less than yâ);
x=x*2;
if (x==y) System.out.println(âx now equal to yâ);
x=x+2;
if (x>y) System.out.println(âx now greater than
yâ);
}
}
29. 29
Lab Assignments
1. Write a program to display the following
output
My name is ______
I am ____ years old
I study in IEP2 at LCCT
30. 30
Example 5
package example5;
public static void main(String args[]) {
int x,y;
y=20;
for(x=0; x<10; x++) {
System.out.println(âThis is x:â +x);
System.out.println(âThis is Y:â +y);
y=y-2;
}
}
}
31. 31
Seperators
Symbol Name Purpose
( ) Parentheses Used to contain list of
parameters
{ } Braces Used to maintain the
value of arrays
[ ] Brackets Used to declare array type
; Semicolon Terminates statements
, Comma Used to chain statements
together inside a for
statement
. Period Used to separate package
names and variables
32. 32
Data Types
⢠Integers
â This group includes byte, short, int, long which are for whole
valued signed numbers.
⢠Floating-point numbers
â This group includes float and double, which represent numbers with
fractional precision.
⢠Characters
â This group includes char, which represents symbols in a character
set, like letters and numbers.
⢠Boolean
â This group includes boolean, which is a special type for
representing true/false values.
34. 34
Example 6
package example6;
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
lightspeed = 186000;
days=1000; // number of days
seconds=days * 24 * 60 * 60; // convert to seconds
distance=lightspeed * seconds; // compute distance
System.out.print(âIn â + days);
System.out.print(â days light will travel about â);
System.out.println(distance + â miles.â);
}
}
36. 36
Example 7
package example7;
public static void main(String args[]) {
double pi, r, a;
r= 10.8; // radius of circle
pi=3.1416; // value of pi
a= pi * r * r; // compute area
System.out.println(âArea of circle is: â + a);
}
}
37. 37
Example 8 (Character)
package example8;
public static void main(String args[]) {
char ch1, ch2;
ch1=88; // code for X
ch2= âYâ;
System.out.print (âch1 and ch2: â);
System.out.println(ch1 + â â +ch2);
}
}
38. 38
Example 9 (Character)
package example9;
public static void main(String args[]) {
char ch1;
ch1=âXâ;
System.out.println (âch1 contains: â + ch1);
ch1++; // increment ch1
System.out.println(âch1 is now â +ch1);
}
}
39. 39
Example 10 (Booleans)
package example10;
public static void main(String args[]) {
boolean b;
b = false;
System.out.println(âb is â +b);
b=true;
System.out.println(âb is â +b);
}
}
40. 40
Example 11
(Dynamic Initialization)
package example11;
public static void main(String args[]) {
double a=3.0, b=4.0;
// c is dynamically initialized
double c = Math.sqrt(a*a + b*b);
System.out.println(âHypotenuse is â +c);
}
}
41. 41
Example12
(Variable life time)
package example12;
public static void main(String args[]) {
int x;
for(x=0; x<3; x++) {
int y=-1; // y is initialized each time
System.out.println(âY is: â +y); //this always prints -1
y=100;
System.out.println(âY is now: â +y);
}
}
}
42. 42
Example 13
(Automatic Conversions)
package example 13;
public static void main(String args[]) {
byte b;
int i=257;
double d=323.142;
System.out.println(ânConversion of int to byte.â);
b=(byte) i;
System.out.println(âi and b â + i + â â +b);
System.out.println(ânConversion of double to int.â);
i=(int) d;
System.out.println(âd and i â + d + â â +i);
System.out.println(ânConversion of double to byte.â);
b=(byte) d;
System.out.println(âd and b â + d + â â +b);
}
}
43. 43
Arrays
⢠An array is a group of like-typed variables
that are referred to by a common name.
⢠One-dimensional Arrays
Syntax,
type var-name[];
Example,
int month_days[];
44. 44
Example 14
(One-Dimensional Arrays)
package example14;
public static void main(String args[]) {
int month_days[];
month_days = new int[12];
month_days[0]=31;
month_days[1]=28;
month_days[2]=31;
month_days[3]=30;
month_days[4]=31;
month_days[5]=30;
month_days[6]=31;
month_days[7]=31;
month_days[8]=30;
month_days[9]=31;
month_days[10]=30;
month_days[11]=31;
System.out.println(âApril hasâ + month_days[3] + âdaysâ);
}
}
49. 49
Example 18
(Two-Dimensional Arrays)
package example18;
public static void main(String args[]) {
int twoD[] []= new int [4] [ ];
twoD[0] = new int [1];
twoD[1] = new int [2];
twoD[2] = new int [3];
twoD[3] = new int [4];
int i,j,k=0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j]=k;
k++;
}
for(i=0; i<4; i++){
for(j=0; j<i+1; j++)
System.out.print (twoD[i][j] + â â);
System.out.println();
}
}
}
59. 59
Example 22
(Modulas Operator)
⢠The modulus operator, % returns the remainder of a
division operator.
package example22;
public static void main(String args[]) {
int x= 42;
double y=42.25;
System.out.println (âx mod 10= â + x % 10);
System.out.println (ây mod 10= â + y % 10);
}
}
60. 60
Example 23
(Arithmetic Assignment Operator)
package example23;
public static void main(String args[]) {
int a=1;
int b=2;
int c=3;
a+=5;
b*=4;
c+=a*b;
c%=6;
System.out.println(âa = â + a);
System.out.println(âb = â + b);
System.out.println(âc = â + c);
}
}
61. 61
Example 24
(Increment & Decrement)
package example24;
public static void main(String args[]) {
int a=1;
int b=2;
int c;
int d;
c= ++b;
d=a++;
c++;
System.out.println(âa = â + a );
System.out.println(âb = â + b );
System.out.println(âc = â + c );
System.out.println(âd = â + d );
}
}
62. 62
Relational & Logical Operators
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
& Logical AND
| Logical OR
?: Ternary if-then-else
63. 63
Example 25
(The ? Operator)
Syntax:
expression1 ? Expression 2 : Expression 3
package example25;
public static void main(String args[]) {
int i,k;
i=10;
k=i<0 ? -i: i;
System.out.println(âi = â + k );
}
}
64. 64
Control Statements
⢠If is used to route program execution through two
different paths.
Syntax:
if (condition) statement1;
else statement2;
Example:
int a,b;
if (a<b) a=0;
else
b=0;
65. 65
IF Statement
Example 26
package example26;
public static void main(String args[]) {
int i,k;
i=10;
k=20;
if (i<k) System.out.println(âi is less than kâ );
else System.out.println(âk is less than iâ);
}
}
66. 66
Nested IF Statement
package example27;
public static void main(String args[]) {
int month = 4;
String season;
if (month == 12 || month == 1 || month == 2)
season=âWinterâ;
else if (month == 3 || month == 4 || month == 5)
season=âSpringâ;
else if (month == 6 || month == 7 || month == 8)
season=âSummerâ;
else if (month == 9 || month == 10 || month == 11)
season=âAutumnâ;
else
season=âBogus Monthâ;
System.out.println(âApril is in the â + season + â.â );
}
}
67. 67
Switch Case
package example28;
public static void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season=âWinterâ;
break;
case 3:
case 4:
case 5:
season=âSpringâ;
break;
68. 68
Switch Case
case 6:
case 7:
case 8:
season=âSummerâ;
break;
case 9:
case 10:
case 11:
season=âAutumnâ;
break;
default:
season=âBogus Seasonâ;
}
System.out.println(âApril is in the â + season + â.â );
}
}
69. 69
Input Example 1
⢠Write a program to input a number and
check whether this number is even or odd.
75. 75
Input Example 4
⢠Write a program to input three numbers
and print the numbers in ascending order.
First number = 7
Second number = 3
Third number = 5
Output
3
5
7
81. 81
Code
import java.io.*;
public static void main(String s[]) throws IOException{
int n,i;
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
System.out.println("Enter how many times? ");
String x=I.readLine();
n=Integer.parseInt(x);
for(i=1; i<=n; i++)
{
System.out.println(âYour nameâ);
}
}
}
82. 82
⢠For_Example2
⢠Write a program to enter n numbers and
display their sum.
How many numbers? 3
Enter number 1 5
Enter number 2 10
Enter number 3 5
Sum = 20
83. 83
Codeimport java.io.*;
public static void main(String s[]) throws IOException{
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
int i,n,sum,num;
sum=0;
System.out.println("Enter how many numbers");
String x=I.readLine();
n=Integer.parseInt(x);
for(i=1;i<=n;i++)
{
System.out.println("Enter number "+ i );
num=Integer.parseInt(I.readLine());
sum=sum+num;
}
System.out.println("Sum= "+sum);
}
}
84. 84
⢠For_Example3
⢠Write a program to find the sum of the
following series:
12 + 32 + 52 +âŚâŚâŚ+ upto nth terms.
87. 87
String Handling
⢠5.1
⢠Write a program to enter a string and print
this string in reverse order
⢠Example:
lampang
gnapmal
88. 88
String Handling
Example 5.1
import java.io.*;
public static void main(String s[])throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
int i,l;
System.out.println("Enter a string");
String str=I.readLine();
l=str.length();
for(i=l-1;i>=0;i--)
{
System.out.print(str.substring(i,i+1));
}
}
}
89. 89
String Handling
⢠5.2
⢠Write a program to enter a string and print
initial character of each word of the string.
⢠Example:
input: Read Only Memory
output: ROM
91. 91
String Handling
⢠5.3
⢠Write a program to enter a string print it in the following format.
⢠Example:
input: HELLO
output:
H
H E
H E L
H E L L
H E L L O
92. 92
String Handling
Example 5.3import java.io.*;
public static void main(String s[])throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
String str;
int i,l,j;
System.out.println("Enter a string");
str=I.readLine();
l=str.length();
for(i=1;i<=l;i++)
{
System.out.print(str.substring(0,i));
}
}
}
93. 93
String Handling
⢠5.4
⢠Write a program to enter a string print it in the following format.
⢠Example:
input: HELLO
output:
H E L L O
H E L L
H E L
H E
H
94. 94
String Handling
Example 5.4import java.io.*;
public static void main(String s[])throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
String str;
int i,l,j;
System.out.println("Enter a string");
str=I.readLine();
l=str.length();
for(i=l;i>=1;i--)
{
System.out.print(str.substring(0,i));
}
}
}
95. 95
String Handling
⢠5.5
⢠Write a program to enter a string print it in the following format.
⢠Example:
input: HELLO
output:
H E L L O
E L L O
L L O
L O
O
96. 96
String Handling
Example 5.5import java.io.*;
public static void main(String s[])throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
String str;
int i,l,j;
System.out.println("Enter a string");
str=I.readLine();
l=str.length();
for(i=0;i<=l-1;i++)
{
System.out.print(str.substring(i,5));
}
}
}
97. 97
String Handling
⢠5.6
⢠Write a program to enter a string print it in the following format.
⢠Example:
input: HELLO
output:
O
L O
L L O
E L L O
H E L L O
98. 98
String Handling
Example 5.6import java.io.*;
public static void main(String s[])throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
String str;
int i,l,j;
System.out.println("Enter a string");
str=I.readLine();
l=str.length();
for(i=l-1;i>=0;i--)
{
System.out.print(str.substring(i,5));
}
}
}
99. 99
Review
Enter how many subjects? 3
Enter marks in subject1: 90
Enter marks in subject2: 60
Enter marks in subject3: 80
Grade = 3
100. 100
Solution
public static void main(String s[])throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
int i,n,num,sum,grade,gpa;
sum=0;
System.out.println("Enter how many subjects: ");
String x =I.readLine();
n=Integer.parseInt(x);
for(i=1;i<=n;i++)
{
System.out.println("Enter marks of subject " + i + ": ");
num=Integer.parseInt(I.readLine());
sum=sum+num;
}
101. 101
Solution
gpa= sum / n;
if (gpa >=80 && gpa<=100)
grade=4;
else if
(gpa >=70 && gpa <= 79)
grade=3;
else if
(gpa >=60 && gpa <=69)
grade=2;
else if
(gpa >=50 && gpa <=59)
grade=1;
else
grade=0;
System.out.println("Grade= " + grade);
}
}
102. 102
Exercise - 1
⢠Write a program to enter the monthly
salary and display the income tax with the
help of following table
Monthly Salary Income Tax
7,499 baht or less 20 % of monthly salary
7,500 â 9,999 30 % of monthly salary
10,000 or more 40 % of monthly salary
103. 103
Exercise - 2
*** MENU ***
1.To find area of rectangle
2. To find area of circle
3. To find area of square
Enter your choice: 1
Enter length & width ?
Area of rectangle=?
104. 104
Exercise - 2
*** MENU ***
1.To find area of rectangle
2. To find area of circle
3. To find area of square
Enter your choice: 2
Enter radius of circle ?
Area of circle=?
105. 105
Exercise - 2
*** MENU ***
1.To find area of rectangle
2. To find area of circle
3. To find area of square
Enter your choice: 3
Enter side of square ?
Area of square=?
106. 106
Solution
public static void main(String s[]) throws IOException
{
InputStreamReader R= new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
int ch,l,w,side,arrect,arsq;
double r,arcir;
compute ob=new compute();
System.out.println(" *** MENU *** ");
System.out.println("1.To find area of rectangle");
System.out.println("2. To find area of circle");
System.out.println("3. To find area of square");
System.out.println("Enter your choice:");
ch=Integer.parseInt(I.readLine());
108. 108
Solution
case 2:
{
System.out.print("Enter radius of circle");
r=Double.parseDouble(I.readLine());
arcir=ob.area(r);
System.out.print("Area of circle =" +arcir);
break;
}
case 3:
{
System.out.print("Enter side of square");
side=Integer.parseInt(I.readLine());
arsq=ob.area(side);
System.out.print("Area of square=" +arsq);
break;
}
default:
System.out.print("Invalid choice");
}
}
}
109. 109
Exercise
Enter how many numbers? 3
Enter number 1: 5
Enter number 2: 7
Enter number 3: 2
Minimum number = 2
Maximum number = 7
110. 110
Solution
public static void main(String s[]) throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
int n,num,i,max,min,sum,avg;
max=0;
min=100;
sum=0;
System.out.println("Enter how many numbers: ");
String x =I.readLine();
n=Integer.parseInt(x);
for(i=1;i<=n;i++)
{
System.out.println("Enter number " + i + ": ");
num=Integer.parseInt(I.readLine());
111. 111
Solution
sum=sum+num;
if (num > max)
max=num;
else
max=max;
if (num<min)
min=num;
else
min=min;
}
avg=sum/n;
System.out.println("Maximum Number :" +max);
System.out.println("Minimun Number :" +min);
System.out.println(âAverage Number :â +avg);
}
112. 112
Exercise
Enter how many products: 2
Enter product price 1:$ 50
Enter product price 2:$ 50
Enter discount % :$ 10
Total Price =$ 90
113. 113
public static void main(String s[]) throws IOException {
InputStreamReader R=new InputStreamReader (System.in);
BufferedReader I=new BufferedReader(R);
int n,i,sum,num,d;
sum=0;
System.out.println("Enter how many products: ");
String x =I.readLine();
n=Integer.parseInt(x);
for(i=1;i<=n;i++)
{
System.out.println("Enter product price " + i + ": ");
num=Integer.parseInt(I.readLine());
sum=sum+num;
}
System.out.println("Enter discount % :");
String y =I.readLine();
d=Integer.parseInt(y);
sum= sum-(sum*d/100);
System.out.println("Total Price =" + sum);
}
}
114. 114
public static void main(String s[]) throws IOException {
InputStreamReader R=new InputStreamReader
(System.in);
BufferedReader I=new BufferedReader(R);
int n,i,m;
System.out.println("Enter number: ");
String x =I.readLine();
n=Integer.parseInt(x);
for(i=1;i<=10;i++)
{
m=i*n;
System.out.println(n + "*"+ i + "=" +m);
}
}
}
115. 115
Exercise
Enter number1: 2
Enter number2: 2
** Select Operation **
** a add(+) **
** s sub(-) **
** m mul(*) **
** d div(/) **
Enter your choice: a
Addition of 2 + 2 = 4