This document provides an introduction to Java programming concepts including: - Java is both a programming language and platform that is simple, architecture neutral, object-oriented, and portable. - Java source code is written in .java files and compiled into .class files by javac before being executed by the Java Virtual Machine (JVM). - The JVM allows Java programs to run on any platform without recompilation, providing platform independence. - Key Java concepts covered include objects, classes, methods, variables, data types, operators, control flow, and arrays. - Examples demonstrate how to write, compile, and run simple Java programs to illustrate these core programming concepts.
2 About the JAVATechnology • 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 JAVATechnology • 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 Namethe 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 Importantfeatures 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 Whatis 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 JAVATechnology • The Java launcher tool (java) then runs your application with an instance of the Java Virtual Machine.
9 About the JAVATechnology • 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 ofObjects 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 Whatis 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 FirstApplication • 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 SourceFile • 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 Compile the SourceFile • 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 aproject • 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 newprogram • 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 inthe 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 theprogram • /** Creates a new instance of Main */ • This is a comment
22 Explanation of theprogram • public static void main(String[ ] args) { • This line begins the main() method.
23.
23 Explanation of theprogram • // 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 theprogram • 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; publicstatic 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; publicstatic 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 Lab Assignments 1. Writea 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; publicstatic 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 Example 6 package example6; publicstatic 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 Example 7 package example7; publicstatic 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) packageexample8; 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) packageexample9; 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) packageexample10; 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) packageexample11; 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) packageexample12; 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) packageexample 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 arrayis 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) packageexample14; 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 Example 18 (Two-Dimensional Arrays) packageexample18; 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 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 AssignmentOperator) 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 & LogicalOperators 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 • Ifis 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 packageexample26; 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 packageexample27; 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; publicstatic 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: case7: 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 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 Code import java.io.*; public staticvoid 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 • Writea 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 staticvoid 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 • Writea program to find the sum of the following series: 12 + 32 + 52 +………+ upto nth terms.
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 importjava.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 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.3importjava.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.4importjava.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.5importjava.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.6importjava.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 manysubjects? 3 Enter marks in subject1: 90 Enter marks in subject2: 60 Enter marks in subject3: 80 Grade = 3
100.
100 Solution public static voidmain(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 voidmain(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 Solution case 2: { System.out.print("Enter radiusof 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 manynumbers? 3 Enter number 1: 5 Enter number 2: 7 Enter number 3: 2 Minimum number = 2 Maximum number = 7
110.
110 Solution public static voidmain(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 manyproducts: 2 Enter product price 1:$ 50 Enter product price 2:$ 50 Enter discount % :$ 10 Total Price =$ 90
113.
113 public static voidmain(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 voidmain(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 Enternumber2: 2 ** Select Operation ** ** a add(+) ** ** s sub(-) ** ** m mul(*) ** ** d div(/) ** Enter your choice: a Addition of 2 + 2 = 4