Download presentation
Presentation is loading. Please wait.
1
Java programming Prof.Rohini S Hanchate
Pimpri Chinchawad polytechnic (PCP) Visit for more Learning Resources
2
Contents History of java. Why java???? Java Introduction Java Features
How Java Differs from other Object Oriented languages
3
Why java???? It’s entirely object-oriented
It has a vast library of predefined objects and operations It’s more platform independent this makes it great for Web programming It’s more secure It isn’t C++
4
Why java???? C : structured language, complexity of program is reduced but fails to achieve bug-free, easy maintain & re-usability OOP: Object and classes Data abstraction & encapsulation Inheritance Polymorphism Dynamic binding message communication
5
Java - An Introduction Java - The new programming language developed by Sun Microsystems in 1991. Originally called Oak by James Gosling, one of the inventors of the Java Language. Java Authors: James , Arthur Van , and others Java is purely object oriented.
6
Java Introduction Originally created for consumer electronics (TV, VCR, Freeze, Washing Machine, Mobile Phone). Java - Machine Independent language Java is language of Internet Programming. It allows you to publish a webpage with Java code in it.
7
Java Milestones Year Development 1990
Sun decided to developed special software that could be used for electronic devices. A project called Green Project created and head by James Gosling. 1991 Explored possibility of using C++, with some updates announced a new language named “Oak” 1992 The team demonstrated the application of their new language to control a list of home appliances using a hand held device. 1993 The World Wide Web appeared on the Internet and transformed the text-based interface to a graphical rich environment. The team developed Web applets (time programs) that could run on all types of computers connected to the Internet.
8
Java Milestones Year Development 1994
The team developed a new Web browsed called “Hot Java” to locate and run Applets. HotJava gained instance success. 1995 Oak was renamed to Java, as it did not survive “legal” registration. Many companies such as Netscape and Microsoft announced their support for Java 1996 Java established itself it self as “the language for Internet programming” and Object Oriented language. 1997- A class libraries, Community effort and standardization, Enterprise Java, Clustering, etc..
9
Java Creation Trouble with C & C++ they are designed to compile specific target or code. The compiler are to expensive & time consuming. To create an easier & more cost effective solution to achieve platform independent language that could be used to create software which can be embedded in various electronic devices eg: oven remote controls etc. Dynamic and Extensible
10
Java features Familiar, Simple, Small Compiled and Interpreted
Platform-Independent and Portable Object-Oriented Robust and Secure Distributed Multi-threaded and Interactive High Performance Dynamic and Extensible Easy of development Scalability and performance
11
Familiar,Simple,Small Familiar, Simple, Small: uses concept of c & C++. Very simple to understand & to write programs. Small : uses numerous methods to solve the delinquent.
12
Compiled Languages (Eg C,C++)
Programmer Object Code Executable Code Source Code Text Editor Compiler linker .c file .o file a.out file Notepad, emacs,vi gcc
13
Java is Compiled and Interpreted
Programmer Hardware and Operating System Source Code Byte Code Text Editor Compiler Interpreter .java file .class file java appletviewer netscape Notepad, emacs,vi javac
14
Architecture Neutral & Portable
Java Compiler - Java source code(.java file) to byte code (file with .class) Bytecode - an intermediate form, closer to machine representation contains set of instructions which is executed by Java runtime System(JVM) A interpreter interprets the bytecode. Porting the java system to any new platform any where any time we need only JVM needs to be implemented for each platform. The interpreter will figure out what the equivalent machine dependent code to run.
15
Total Platform Independence
JAVA COMPILER (translator) JAVA BYTE CODE (same for all platforms) JAVA INTERPRETER (one for each different system) Windows 95 Macintosh Solaris Windows NT
16
Security & Robust Using Java compatible web browser we can safely download Java programs as it provides firewall between network based application and System. Java is strictly typed language it checks code at compile time & run time. All the run time errors can be handled by programs. Robust: all memory management through garbage collection.
17
High performance & Distributed
Byte code interpreted on any system that provide JVM Perform well on low powered CPU's .byte code is designed to translate directly into native m/c code. To achieve high performance using JIT compiler. Distributed: it support TCP/IP protocol ,accessing resource using URL ,support RMI. Allow multiple programmers at multiple remote locations
18
Rich Class Environment
Core Classes language Utilities Input/Output Low-Level Networking Graphical User Interface Internet Classes TCP/IP Networking WWW and HTML Distributed Programs
19
Overlap of C, C++, and Java
20
Java better than C++ ? No Typedefs, Defines, or Preprocessor
No Global Variables No Goto statements No Pointers No Unsafe Structures No Multiple Inheritance No Operator Overloading
21
Object Oriented Languages -A Comparison
Features C++ C Java Encapsulation Yes Inheritance Multiple Inherit. No Polymorphism Binding (Early or Late) Both Late Concurrency Poor Garbage Collection Class Libraries
22
Simple java program Class first_program {
Public static void main(String args[]) System.out.println(“hellow world”); } } Class method
23
Simple java program cntd...
Public: The keyword public is an access specifiers that declares the main method as unprotected. Static: Which declares main method as one that belongs to the entire class ,The main must always declare as static since the interpreter uses this method before any objects are created. Void: The type modifier void states that the main method does not return any value.
24
JAVA Tokens Smallest individual units in a program are known as Tokens. Five different types of tokens: Reserved Keywords. (60 Keywords, false, null, true, package etc.,). Identifiers (alphabets, digits and underscore and dollar sign characters.) Literals. (Integer, Floating Point. Character, String, Boolean) Operators. Separators.
25
Tokens cntd.... (Keywords)
Java language is having reserved 50 word as keywords. abstract assert boolean break byte case catch char class const continue deafult do double Else enum extends final finally float for goto if implements import instanceof int interface long native new packages private protected public return short static strichfp super switch synchronized this throw throws transient try void volitile while
26
Tokens cntd.... (identifiers)
These are programer designed tokens. Classes. Methods Variables. Objects Labels Packages Interfaces
27
Identfiers cntd... Rules for identifiers:
Alphabets,digits,underscore(_)and $ are allowed. They must not begin with digit. Uppercase and lowercase letters are distinct. Identifier can be of any length. Identfiers must be meaningful. Short, easy, quick. Easily readable and discriptive. Eg: average, dayTemerature,first_name,TOTAL.
28
Literals Literals are sequence of characters. 5 types of literals
Integer literals Floating point literals Charester literals String literals Boolean literals
29
Operators An operator is symbol that takes one or more arguments and operates on them to produce results.
30
Separators Symbols used to indicate where groups of code are divided and arranged. Parentheses () Method definition and invocation, defining precedence in expressions Braces {} Define a block of code for classes, methods and local scopes Brackets [] Declare array types and for dereferencing array values. Semicolon ; Separate the statements. Comma , Consecutive identifiers in a variable declaration and chain statements (For loop and int a,b) Period . Separate package names from the sub-packages and class, separate a variable or method from a reference variable.
31
Constants Constant in java refered to fixed values that do not change during execution of a program. Numeric constants Integer constants Real constants Charecter constants Charechter constants String constants
32
Backslash character constants
meaning ‘\b’ Back Space. ‘\f’ Form Feed. ‘\n’ New line ‘\t’ Horizontal tab ' \ ' Single quote '\\' backslash
33
Constants cntd.... Integer constants: it refer as sequence of digits
Decimal integer constant consist of set of digit from 0 to 9 eg. 123 Octal integer constants consist of from 0 to 7 eg. 037,0435 Real constants: numbers contain fractional parts refered to real constants eg Character constants: single character enclosed within a pair of single quotes eg. '4','a'. String constants: a sequence of charater encloused with in double qoutes eg. “hello”,”1998”.
34
Symbolic constants Symbolic names take the same form as variable names. SC's are written in CAPITALS to distinguish them from normal variable names. they should not be assigned any other value within the program after declaration of symbolic constants by using an assignment statement. eg. final int PEOPLE = 100; //we can not change the value. This is not done in C and C++ where it is defined using the #define statement. Can not be declared inside a method.
35
Data types Every variable is having Data type
Data type specify size and type of values that can be stored. Depend on need of application select appropriate data type Category of Data Types Primitive type Derived type
36
DT cntd…
37
Integer types Java support 4 types of integers.
38
Floating point Data types
Size Value Float 4 bytes 3.4e-038 to 3.4e+038 Double 8 bytes 1.7e-308 to 1.7e+308
39
Data Type cntd.. Character type
To store character constants in memory. Size is 2 bytes Boolean type To test particular condition we use Boolean type. Only two values it takes True & False. All comparison operators return Boolean type.
40
Standard default values
Every variable has default values. Type of variable Default values Byte 0(zero) Short int Long 0L Float 0.0f Double 0.0d Char Null Boolean False Reference null
41
Variables Variable is an identifier that denotes a storage location used to store data value. Rules for defining variable Variable may take different value at different times during execution of the program Variable name should be Meaningful . Variable must not begin with a digit. Uppercase and lower case letters are distinct. It should not be keyword. White spaces is not allowed Variable name can be anything.
42
Declaration of variables
Variable are names of storage locations. After designing suitable variable names we must declare them to the compiler Why declaration????? It tells the variable name to compiler Type of data that variable holding Place of variable decides scope of the variables Variable must be declared before it used in program Variable used to store value of any data type.
43
Declaration of variable cntd…
Type variable1,variable2,variable3…….; Variables are separated by comma’s (,) Declaration statement should end with ; . Eg , int count; float area; double p1; char c1,c2,c3;
44
Assigning values to variables
Using assignment statement Variable_Name = value; Eg intialValue=0; finalValue=100; String assignment eg x=y=z=0; Assign values at declaration time Eg int finalValue=100; Char yes = ‘x’;
45
Scope of variable Instance or object variable Class variable
Local variable Instance and class variables are declared inside a class. Instance variables are created when the object are initiated and those variables are associated with the object. Instance variable take different values for each object Class variables are global to class. Belongs to objects that class creates Only one memory location is created for class variables.
46
Local variable: Variables used and defined inside the method are local variables
Not available to outside the method definition.
47
Example for variables Eg : class myprg { Int z=10; class variable
method1; { int x=0; \\ local variable int n=5; \\ only with in braces } Public static void main(String args[]) First f=new First();\\ instance variable
48
Type casting Want store variable of one type in into a variable of other type. Type variable1 = (type) variable2; It is converting one data type to another is known as casting. Eg int m= 12; byte n =(byte) m; Long count = (long) m;
49
Casting with no loss of information
From To Byte Short,char,int,long,float,double Short Int,long,float,double Char Int Long,float,double Long Float,double Float double
50
Reading data from Keyboard
Import java.lang.*; Import java.io.DataInputStream; Class read { public static void main (String args []) DataInputStream in = new DataInputStream (System. in); int num = 0; System.out.println (“Enter a number :”); num = Integer.parseInt (in.readLine () ); System.out.println (“entered number Num = “ +num); }
51
Output: Enter a Number: 123 entered number Num = 123
52
Reading input from scanner
import java.util.Scanner; class ScannerTest { public static void main(String args[]) { Scanner sc=new Scanner(System.in); System.out.println("Enter your rollno"); int rollno=sc.nextInt(); System.out.println("Enter your name"); String name=sc.next(); System.out.println("Enter your fee"); double fee=sc.nextDouble(); System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee); sc.close(); } }
53
Reading input from scanner
54
Operators Arithmetic operators
55
Relational operators: Compare two quantities and depend on their relation take certain decisions.
Meaning Example < Less than a<b <= Less than or equal to 4.5<=10 > Greater than b>c >= Greater than or equal to -35>=0 == Equal to a+b==c+d != Not equal to i%2!=0
56
Logical operators Operator Meaning Example && Logical AND
a>b && x==10 || Logical OR if(a<0||b>100) ! Logical NOT a!=b
57
Increment & decrement operators
++ increments the value of its operand by 1. -- decrements the value of its operand by 1. Syntax: Pre-increment: ++variable Post-increment: variable++ Pre-decrement: --variable Post-decrement: variable--
58
Increment (++) operator it is used in for and while loops.
Eg. ++m, m++ or m=m+1, or m+=1; Decrement operator (--) : Eg: --m, m=m-1,m-=1;
59
Example of Operator Class increment_operator {
Public static void main(String args[]) Int m=10,n=20; System.out.println(“m = “ +m); System.out.println(“n = “ +n); System.out.println(“++m = “ + ++m); System.out.println(“n++ = “ + n++); }
60
Output M=10 N =20 ++m=11 N++ =20 M=11 N=21
Eg: a[i++] =10; Or a[i] = 10 i=i+1;
61
Conditional operator To construct conditional expressions
exp1 ? exp2 : exp3 Where exp1,exp2,exp3 are expressions Exp1 is true then execute exp2 Exp1 is false then execute exp3 Only one expression is evaluated Eg: a=10,b=15,x=(a>b)? a : b
62
Bitwise operators Manipulation of data at values of bit level.
This operator is used to testing bits or shifting bits right or left Not applicable to float or double Operator Meaning & Bitwise AND ! Bitwise OR ^ Bitwise exclusive OR ~ One’s complicate << Shift left >> Shift right >>> Shift right with zero fill
63
Person instanceof student
Special operator Java supports instanceof operator and member selection operator dot(.). Instanceof operator: is object reference operator. If object is instance of the given class Person instanceof student Above statement is true if object person is belongs to class student. DOT operator (.): Access the instance variable and methods of class objects. Access classes and sub-packages from a package Person1.age; //reference to variable age Person1.salary() //reference to method salary()
64
Assignment operator Assign value of an expression to variable
Variable1 op = exp; x+=y+1; V1 = v2 op(exp); X=x+(y+1); Or X++; x=x+1;
65
Operator precedence Expression with no parentheses evaluate from left to right High priority * / % Low priority Eg: x=a-b/3+c*2-1
66
Expressions Integral expressions Floating-point or decimal expressions
Mixed expressions
67
Integral expressions All operands are integers. Examples: 2 + 3 * 5
3 + x – y / 7 x + 2 * (y – z) + 18
68
Floating-point expressions
All operands are floating-point numbers. Examples: 12.8 * 17.5 – 34.50 x * y
69
Mixed Expressions Operands of different types. Examples: 2 + 3.5
6 / Integer operands yield an integer result. floating-point numbers yield floating-point results. If both types of operands are present, the result is a floating-point number.
70
Evaluation expressions
Expressions are evaluated using an assignment operator. Variable = expression; Eg; x=a*b-c; y=b/c*a;
71
Type converssion of expression
Automatic type conversion. Generic type conversions Used to avoid implicit type coercion. Syntax: (dataTypeName) expression Expression evaluated first, then type converted to: dataTypeName Examples: (int)( ) = 14 (int)(7.9) + (int)(6.7) = 13
72
Type converssions cntd..
Float to int causes truncation of fractional part Double to float causes rounding of digits Long to int causes dropping of the higher order bits Type converssions Data type Promoted/Converted to Byte,short,int int long Int except 1 or L is appended float double
73
Type converssions cntd..
Casting values: Syntax : (type_name) expression Eg, x= (int) 7.5 a=(int)21.8/(int) 3.4 b=(double) sum/n : division by floating mode Y = (int) (a+b) X= (int) (y+0.5)
74
Casting operation for expression example
Class casting { Public static void main(String args[]) Float sum; Int i; Sum= 0.0F; For(i=1;i<=10;i++) sum=sum+1/(float) i; Syetem.out.print(“i = “ +i); Syetem.out.print(“sum = “ +sum); } } }
75
Operator precedence and associativity
76
Mathematical functions
Math class is defined in java.lang packages. Math.function_name(); Eg double y = Math.sqrt();
77
Mathematical functions
78
Creating constructor class
class Student { int id; String name; Student(int i,String n) id = i; name = n; } void display() System.out.println(id+"\n "+name); public static void main(String args[]) Student s1 = new Student(111, "Karan"); Student s2 = new Student(222,"Aryan"); s1.display(); s2.display();
79
Creating constructor class
Create class Student which is having data members st_ID,Name,Dept. Accept student data by get_data() method and display student information using put_data() method. Create class Employee which is having data members emp_ID,EName,EDept. Accept employee data by get_data() method and display employee information using put_data() method. Create class Rectangle which is having data members length,breadth,hight. Accept data by get_data() method and display area of Reactangle by using put_data() method.
80
Decision Making and Looping
Control or decision making statment: it used to control the flow of execution of statement If statement If-else statement Nested if else If else ladder Switch statement Nested switch Conditional operator
81
If statment Determines whether it is true or false
Uses logical operators to compare values Syntax: Eg if(age>60) { Sytem.out.print(“Retired person”); } Sytem.out.print(“all are working on govt office”); if(test expression) { Statement_ block; } statement_x;
82
if...else statement Syntax if(test expression) {
True block Statements; } else False block statements; statement_x;
83
Nested if..else statement
if(test condition1) { if(test condition2) statement—1; } else statement--2; statement—3; statement_x; Syntax:
84
Else...if ladder Syntax: if(test condition1) else if(test condition2)
statement—1; else if(test condition2) statement—2; else if(condition3) statement—3; else if( condtion n) statement—n; else default-statement; statement_x; Syntax:
85
Switch statement To reduce complexity of program. Readable statements.
Reduces Mis-perception of program. Java multi-ways of decision making statements known as switch. Set of statements are tested against list of cases when match is found a block of statement is executed.
86
Switch Syntax Switch(expression) { Case value-1: block-1 break;
……………… Default : default –block; } Statement-x;
87
Switch Example Class Demo_switch {
Public static void main(String args[]) System.out.println(“enter your choice\n”); Char ch = (char) Sytem.in.read(); switch (ch) { case 0: System.out.println(“i am good in java programming”); break; case 1: System.out.println(“i dont know java”); default: System.out.println(“i understand c++”); } }
88
Example of switch public class SwitchExample {
public static void main(String[] args) { int number=20; switch(number){ case 10: System.out.println("10");break; case 20: System.out.println("20");break; case 30: System.out.println("30");break; default:System.out.println("Not in 10, 20 or 30"); }
89
Why break is needed in switch
int i = 1; switch (i) { case 0: System.out.println(“0”); case 1: System.out.println(“1”); case 2: System.out.println(“2”); case 3: System.out.println(“3”); } System.out.println( ); output is:
90
Looping Repeatedly executing blocks is refereed looping.
Statement in block can be executed infinite time start from 0 to infinite number of time. If loop continues it is refereed as infinite loop No goto statements.
91
Control structures
92
Looping process Setting and initialization of a counter (initialization). Execution of the statement in the loop. Test for specified condition(condition). Increment or decrement counter (increment). Java supports While loop Do-while loop For loop
93
While loop Initialization ; While( test condition) { Body of the loop
It is Entry controlled loop statement. Syntax for while loop: Initialization ; While( test condition) { Body of the loop }
94
Program for while loop Class while_program {
Public static void main(String args[]) { System.out.println(“begin of while loop”); Int i=0; While(i<=10) { System.out.println(i); i++; } System.out.println(“end of while loop”);
95
Output Begin of while loop 1 2 3 4 5 6 7 8 9 10 End of while loop
96
Do-While loop Initialization; Do { Body of the loop;
To execute body of loop once Exit control statement Syntax: Initialization; Do { Body of the loop; } while(test condition);
97
class excute_dowhile { Public static void main(String args[]) int count = 0; do count++; System.out.println (count); } while (count < 5); }
98
condition becomes false condition becomes false
For statement The statement is executed until the condition becomes false The statement is executed until the condition becomes false The initialization is executed once before the loop begins for ( initialization ; condition ; increment ) statement; for ( initialization ; condition ; increment ) statement; The increment portion is executed at the end of each iteration The increment portion is executed at the end of each iteration
99
For statement cntd.. For loop executed for specific amount of time
If the initialization is left out, no initialization is performed If the condition is left out, it is always true, and creates an infinite loop If increment is left out, no increment operation is performed Example: for (int count=1; count <= 5; count++) System.out.println (count);
100
Use of break & continue in looping
When break statement is encountered inside a loop, loop immediately exited while(condition) { Statements.... if(condition) Break; Statement.... } Statements... Do Statements.. Statements For() ..... } statements For(condition1) { For((condition2) If(condition) Break; } Statements;
101
Labelled Loops Label is valid variable name ,Labels to block of statements. Assigning label to loops: Loop1: for(condition) { Statement; } Block1: {…… ……. Block2: {
102
Example for labelled loops
Class ContinueBreak { Public static void main(String args[]) LOOP1: for(int i=1;i<10;i++) If(i>=5) break; For(int j=1;j<100;j++) { System.out.println(“*”); If(j==i) Continue LOOP1; } } //termination by break }
103
Nested loops Nested for loop For(i=1;i<4;i++) {
For(j=1;j<=5;++j) Statements; } Nested do-while Do Int X=1; Int y=1; Int c= x+y; }while(x==1); System.out.println(“x=“+x); }while(y==1); System.out.println(“c=“+c);
104
Enhanced for loop To retrieve array elements efficiently instead of using array index. Syntax: For(type identifier : expression) { Statements ; } Example Class loopingEX { P.S.V.M(String args[]){ Int a[3]=[10,20,30]; For(int i:a) If(i>5 &&i<50) System.out.println(“the selected values are”+i); } }
105
For more detail contact us
Perform Assignments WAP to display month names using given the month numbers. WAP to display array values using for loop and for-each loop. given 10,20,30,40,50 For more detail contact us
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.