Download presentation
Presentation is loading. Please wait.
1
Programming in Java http://www.tutorialspoint.com Text Books :
Herbert Schildt, “JAVA 2: Complete Reference”, 5th Edition, TMH Reference Books : Jim Keogh, “J2EE Complete Reference”. Kenarnold and James gosling : “The Java Programming Language”.
2
Programming in Java Module - 1
Introduction to OOP Concepts & Implementation in Java 1. What is Java?-Features of Java 2. C, C++ vs. Java 3. Constants, variables, data types, operators, expressions. 4. OOPs concepts 5. Role of Constructor 6. Memory management using Garbage collector 7. Creating 1D and 2D Arrays
3
Programming in Java Module - 1
Introduction to OOP Concepts & Implementation in Java 8. Overloading and Overriding 9. Use of this and super keywords 10. Inheritance 11. Use of final Keywords 12. Dynamic Binding and Static Binding 13. Run-time Polymorphism 14. Abstract class and Interfaces 15. Inner/Nested classes
4
Difference between Java and C++
Java imports class files. C++ includes header files Java is a object oriented language. C++ is a partially object oriented language. Java does not have destructors. C++ has destructors. Java supports auto garbage collection. does not supports GC, requires memory management does not provide operator overloading facility C++ supports operator overloading. “.class” file is generated after compilation. “.exe” file is generated after compilation Java doesn’t support pointers. C++ supports pointers. Java uses compiler & interpreter both. C++ uses compiler only. Through Java we can develop Distributed /Internet based applications. Development of Distributed / Internet based applications is not possible in C++.
5
Introduction to Java What is Java?
Java is a programming language and a platform. Java is a high level, robust, secured and object-oriented programming language. Platform: Any hardware or software environment in which a program runs, is known as a platform. Since Java has its own runtime environment (JRE) and API, it is called platform.
6
Simple Java Program $ javac Simple.java Complile and Run $ java Simple
class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } $ javac Simple.java $ java Simple Complile and Run
7
Where it is used? There are many devices where java is currently used and are as follows : Desktop Applications such as acrobat reader, media player, antivirus etc. Web Applications such as irctc.co.in, javatpoint.com etc. Enterprise Applications such as banking applications. Mobiles. Embedded System. Smart Card. Robotics and Games etc.
8
Types of Java Applications
There are mainly 4 type of applications that can be created using JAVA 1. Stand alone Applications : Desktop/window-based application. An application that we need to install on every machine such as media player, antivirus etc. AWT and Swing are used in java for creating standalone applications 2. Web Applications : runs on the server side and creates dynamic page Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in java 3. Enterprise Applications It is distributed in nature, such as banking applications etc. It has the advantage of high level security, load balancing and clustering. In java, EJB is used for creating enterprise applications 4. Mobile Applications : An application that is created for mobile devices.
9
History of Java James Gosling
The history of java starts from Green Team. Green team members (James Gosling, Mike Sheridan,and Patrick Naughton) initiated a task to develop a language for digital devices like Set-top boxes, Tv's etc. Initially, it was called "Greentalk" by James Gosling and file ext .gt. After that, it was called “Oak” and was developed as a part of the Green project. James Gosling Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A., France, Germany, Romania etc. Oak was renamed as "Java" because it was already a trademark by Oak Technologies. Java is an island of Indonesia where first coffee was produced (called java coffee)
10
Java Version History JDK Alpha and Beta (1995) JDK 1.0 (23rd Jan, 1996) JDK 1.1 (19th Feb, 1997) J2SE 1.2 (8th Dec, 1998) J2SE 1.3 (8th May, 2000) J2SE 1.4 (6th Feb, 2002) J2SE 5.0 (30th Sep, 2004) Java SE 6 (11th Dec, 2006) Java SE 7 (28th July, 2011) Java SE 8 (18th March, 2014)
11
Features of Java http://www.javatpoint.com/features-of-java
They are also known as java buzzwords Simple Object-Oriented Platform independent Secured Robust Architecture neutral Portable Dynamic Interpreted High Performance Multithreaded Distributed
12
What is Java Program…? Java program can be defined as a collection of objects that communicate via invoking each other's methods. Let us now briefly look into what do class, object, methods and instance variables mean. Object - Objects have states and behaviors. Example: A dog has states – color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class. Class - A class can be defined as a template/ blue print that describes the behaviors/states that object of its type support. Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables.
13
Structure of Java Program…?
14
Java Program… Basic Syntax
It is very important to keep in mind the following points. Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. Class Names - For all class names the first letter should 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 should 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()
15
Java Program… Basic Syntax
It is very important to keep in mind the following points. 4. Program File Name - Name of the program 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). Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'. 5. public static void main(String args[]) - Java program processing starts from the main() method which is a mandatory part of every Java program..
16
Requirement of Hello Java Program
For executing any java program, you need to install the JDK and install it. set path of the jdk/bin directory. Create the java program, Compile and Run the java program class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } $ javac Simple.java $ java Simple Complile and Run
17
Understanding Java Program
class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } $ javac Simple.java $ java Simple Complile and Run class keyword is used to declare a class in java. public keyword is an access modifier which represents visibility. (private/protected) static is a keyword, will not create any object, so it saves memory. void is the return type of the method, it means it doesn't return any value. main represents startup of the program. String[] args is used for command line argument. System.out.println() is used print statement.
18
Understanding Java Program
Compile Time class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } ByteCode javac Simple.java Compiler Simple.java Simple.class Run Time Hardware Class File java Simple.class Class Loader Runtime Byte Code Verifier Interpreter
19
Java Virtual Machine (JVM)
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. Java is platform independent. The JVM performs following main tasks: Loads code Verifies code Executes code Provides runtime environment
20
Java Runtime Environment(JRE)
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment. It is the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime. Implementation of JVMs are also actively released by other companies besides Sun Micro Systems. JRE Set of Libraries JVM Other Files
21
Java Development Kit (JDK)
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools. JRE Development Tools Eg : javac, java Set of Libraries Eg : Jar Files JVM Other Files
22
Java Tokens The Smallest individual units in a program are called tokens. Java language includes 5 types of tokens Reserved/Keywords words Identifiers Literals Operators Separators
23
Java Keywords Abstract Assert boolean break byte case catch Char class const continue default do Double else enum extends final finally Float for goto if implements Import instanceof int interface long Native new package private protected Public return short static strictfp Super switch synchronized this Throw throws transient try Void volatile while
24
Java Identifiers & Literals
Names given to variables, objects, methods Must not be a Java keyword Must begin with a letter. Followed by any number of characters, digits, or _ (Underscore) Identifiers should be well chosen use complete words (even phrases) this helps program documentation Literals Integers 4, 19, -5, 0, 1000 Doubles , 0.0, Strings “Hi Mom” “Enter the number : “ Character 'A' 'X' '9' '$' '\n' Boolean true, false
25
Java Constants A constant in Java is used to map an exact and unchanging value to a variable name. Constants are used in programming to make code a bit more robust and human readable. public class AreasAndVolumes { public double volumeOfSphere (double radius) { return (4/3) * Math.pow( * radius, 3); } public double volumeOfCylinder (double radius, double height) { return Math.pow(radius * , 2) * height; public double areaOfCircle (double radius) { return Math.pow(radius * , 2);
26
Java Constants (final)
A constant in Java is used to map an exact and unchanging value to a variable name. Constants are used in programming to make code a bit more robust and human readable. public class AreasAndVolumes { private static final double PI = ; public double volumnOfSphere (double radius) { return (4/3) * Math.pow( PI * radius, 3); } public double volumeOfCylinder (double radius, double height) { return Math.pow(radius * PI, 2) * height; public double areaOfCircle (double radius) { return Math.pow(radius * PI, 2); final : When you declare a variable to be final, we are telling Java that we will NOT allow the variable’s “pointer” to the value to be changed.
27
Variable and Data Types
Variable : It is name of reserved area allocated in memory. class A{ int data=50; //instance variable static int m=100; //static variable void method() { int n=90; //local variable } //end of method }//end of class RAM x Variable int x=50; There are three types of variables in java 1. local variable : Variable that is declared inside the method is called local variable 2. instance variable : Variable that is declared inside the class but outside the method is called instance variable . It is not declared as static. 3. static variable : A variable that is declared as static is called static variable. It cannot be local.
28
Data Types Two types of data types primitive data types
non-primitive data types
29
Operators Operators Precedence Postfix expr++ expr--
Unary expr --expr +expr -expr ~ ! Multiplicative * / % Additive Shift << >> >>> Relational < > <= >= instanceof Equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || Ternary ? : Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
30
Expressions An expression is a construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value. int Result = 1 + 2; // result is now 3 float Ratio = 3.5f f; Disc = B * B – 4 * A * C; Disc = B * (B – 4 * A) * C; if (value1 == value2) System.out.println("value1 == value2");
31
Statements Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;). Assignment expressions Any use of ++ or -- Method invocations Object creation expressions Expression statements.
32
Statements Here are some examples of expression statements.
AValue = ; // assignment statement Avalue++; // increment statement System.out.println("Hello World!"); // method invocation statement Bicycle myBike = new Bicycle(); // object creation statement Two kinds of statements : Declaration statements and Control flow statements. Declaration statement : It declares a variable. You've seen many examples of declaration statements already: double aValue = ; // declaration statement
33
Example for Decision-making statements
Control Flow Statements : Control flow statements, however, break up the flow of execution by employing decision making, looping, and branching, enabling the program to conditionally execute particular blocks of code. Decision-making statements : (if-then, if-then-else, switch) Looping statements : (for, while, do-while) Branching statements : (break, continue, return) Example for Decision-making statements switch (Condition) { case a : ------ case b : } if (Condition) { ------ } else { } if (Condition) { ------ }
34
Statements Looping Statements : which repeats a statement/block for many times. iVar = 0; While (PreCondition) { ----- } iVar = 0; do { ----- }While (PostCondition) for (iVar = 0; iVar < 10; iVar++) { ------ ----- }
35
Arrays : A data structure : which stores a fixed-size sequential collection of elements of the same type (Homogenous). It is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type. Declaring Array Variables: dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way. double[] myArr; double myArr[]; Creating Arrays: By using the new operator with the following syntax: arrayRefVar = new dataType[arraySize]; The above statement does two things: It creates an array using new dataType[arraySize]; It assigns the reference of the newly created array to the variable arrayRefVar. myArr = new int[20];
36
Processing Arrays : public class TestArray {
public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; total += myList[i]; System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; System.out.println("Max is " + max);
37
import java.util.Scanner;
public class MatrixAddition { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("Enter number of rows and columns: "); int rows = s.nextInt(); int columns = s.nextInt(); int[][] a = new int[rows][columns]; System.out.println("Enter the first matrix"); for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) { a[i][j] = s.nextInt(); } int[][] b = new int[rows][columns]; System.out.println("Enter the second matrix"); b[i][j] = s.nextInt(); int[][] c = new int[rows][columns]; System.out.println("The sum of the two matrices is"); c[i][j] = a[i][j] + b[i][j]; System.out.print(c[i][j] + " "); } } }
38
Passing Array to method in java
class Testarray2{ static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,22,45,3,4,5}; min(a); //passing array to method }
39
Call by Value and Call by Reference
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method. class Operation{ int data=50; void change(int data){ data=data+100; //changes will be in the local variable only } public static void main(String args[]){ Operation op=new Operation(); System.out.println("before change "+op.data); op.change(500); System.out.println("after change "+op.data); } } Output: before change 50 after change 50
40
Call by Value and Call by Reference
class Operation2{ int data=50; void change(Operation2 op){ op.data=op.data+100; //changes will be in the instance variable } public static void main(String args[]){ Operation2 op=new Operation2(); System.out.println("before change "+op.data); op.change(op); //passing object System.out.println("after change "+op.data); } } Output: before change 50 after change 150
41
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt. class CommandLineExample{ public static void main(String args[]){ System.out.println("Your first argument is: "+args[0]); } } javac CommandLineExample.java java CommandLineExample argument Output : Your first argument is: argument
42
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java program. The arguments passed from the console can be received in the java program and it can be used as an input. it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt. class A{ public static void main(String args[]){ for(int i=0;i<args.length;i++) System.out.println(args[i]); } } javac CommandLineExample.java java CommandLineExample kvp jaiswal 1 3 abc Output : kvp jaiswal 1 3 abc
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.