Oop Through Java Programming PDF

Document Details

VigilantOxygen

Uploaded by VigilantOxygen

Tags

Java programming OOP programming languages computer science

Summary

This presentation explains the basics of Java programming, covering its history, key features, and fundamental concepts. It's likely a good starting point for students learning Java or as a refresher for experienced programmers.

Full Transcript

Oop Through Java Programming History of Java  Java was originally designed for interactive television, but it was too advanced technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team members (also known as Green Team), ini...

Oop Through Java Programming History of Java  Java was originally designed for interactive television, but it was too advanced technology for the digital cable television industry at the time. The history of Java starts with the Green Team. Java team members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java technology was incorporated by Netscape. History of Java  The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s.  James Gosling - founder of java  Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc. Java Version History  Many java versions have been released till now. The current stable release of Java is Java SE 10.  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 17 (September 2021)  Java SE 18 (to be released by March 2022) What is Java?  Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure programming language.  Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was already a registered company, so James Gosling and his team changed the name from Oak to Java. Features of Java Features of Java  Simple  Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because:  Java syntax is based on C++ (so easier for programmers to learn it after C++).  Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.  There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java. Features of Java  Object-oriented  Java is an object-oriented programming language. Everything in Java is an object. Object- oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior.  Basic concepts of OOPs are:  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation Features of Java  Platform Independent  Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs.  There are two types of platforms software-based and hardware-based. Java provides a software-based platform.  Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA). Features of Java  Secured  Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:  No explicit pointer  Java Programs run inside a virtual machine sandbox Features of Java  Robust  The English mining of Robust is strong. Java is robust because:  It uses strong memory management.  There is a lack of pointers that avoids security problems.  Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.  There are exception handling and the type checking mechanism in Java. All these points make Java robust. Features of Java  Portable - Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.  High-performance - Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc. Features of Java  Distributed - Java is distributed because it facilitates users to create distributed applications in Java. RMI are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.  Multi-threaded - A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi- media, Web applications, etc. Features of Java  Dynamic - Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++. Java Variables  A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.  Variable is a name of memory location. There are three types of variables in java: local, instance and static. int data=50;//Here data is variable Types of Variables  There are three types of variables in Java:  local variable  instance variable  static variable Types of Variables  Local Variable A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists. A local variable cannot be defined with "static" keyword. Types of Variables  Instance Variable A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.  It is called an instance variable because its value is instance-specific and is not shared among instances. Types of Variables  Static variable A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory. Data Types in Java  Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.  Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays. Data Types in Java Java Comments  TheJava comments are the statements in a program that are not executed by the compiler and interpreter. Types of Java Comments  Java Single Line Comment - The single-line comment is used to comment only one line of the code. It is the widely used and easiest way of commenting the statements.  Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java.  Syntax:  //This is single line comment  Example:-  public class CommentExample1 {  public static void main(String[] args) {  int i=10; // i is a variable with value 10  System.out.println(i); //printing the variable i  } } Types of Java Comments  Java Multi Line Comment - The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line comments there).  Multi-line comments are placed between. Any text between is not executed by Java.  Java Constant  A constant is an entity in programming that is immutable. In other words, the value that cannot be changed. In this section, we will learn about Java constant and how to declare a constant in Java.  What is constant - Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final.  In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.  static final datatype identifier_name=value;  static final double PRICE=432.78; Scope of a Variable  In programming, a variable can be declared and defined inside a class, method, or block. It defines the scope of the variable i.e. the visibility or accessibility of a variable. Variable declared inside a block or method are not visible to outside. If we try to do so, we will get a compilation error. Scope of a Variable  class Scope  {  public static void main (String args[])  {  int x; // known to all code within main  x = 10;  if(x == 10)  { // start new scope  int y = 20; // known only to this block. x and y both known here  System.out.println("x and y: " + x + " " + y);  x = y * 2;  }  y = 100; // Error! y not known here  x is still known here. System.out.println("x is " + x);  }} Declaring a Variable  In Java, all variables must be declared before they can be used. The basic form of a variable declaration is shown  There are two ways to declare a variable in Java. The first method is to assign the initial value to the variable. The second method declares variable without initial value.  Data_type variable_name = value;  Data_type variable_name;  For example: String my_name = "Java coder";  For example: String my_name; Java Variable Declaration Example: Without Initialization  public class DeclareVariable {  public static void main(String[] args) {  int student_id;  String student_name;  System.out.println( student_name);  System.out.println( student_id);  System.out.println( "Name:" +student_name+ "\n Age:" +student_id); Java Variable Declaration Example: With Initialization  public class CreateVariable {  public static void main(String[] args) {  //variable declaration  int student_id = 10;  String student_name = "Java coder";  System.out.println("Name:" +student_name+ "\ nAge:" +student_id);  } } Type Casting in Java  In Java, type casting is a method or process that converts a data type into another data type in both ways manually and automatically. The automatic conversion is done by the compiler and manual conversion performed by the programmer. In this section, we will discuss type casting and its types with proper examples. Types of Type Casting  There are two types of type casting:  Widening Type Casting  Narrowing Type Casting Types of Type Casting  Widening Type Casting - Converting a lower data type into a higher one is called widening type casting. It is also known as implicit conversion or casting down. It is done automatically. It is safe because there is no chance to lose data. It takes place when:  Both data types must be compatible with each other.  The target type must be larger than the source type.  Example:  int a;  byte b; b = (byte) a; Example WideningTypeCasting  public class WideningTypeCastingExample  {  public static void main(String[] args)  {  int x = 7;  //automatically converts the integer type into long type  long y = x;  //automatically converts the long type into float type  float z = y;  System.out.println("Before conversion, int value "+x);  System.out.println("After conversion, long value "+y);  System.out.println("After conversion, float value "+z);  } } Narrowing Type Casting  Converting a higher data type into a lower one is called narrowing type casting. It is also known as explicit conversion or casting up. It is done manually by the programmer. If we do not perform casting then the compiler reports a compile-time error. Example NarrowingTypeCasting  public class NarrowingTypeCastingExample  {  public static void main(String args[])  {  double d = 166.66;  //converting double data type into long data type  long l = (long)d;  //converting long data type into int data type  int i = (int)l;  System.out.println("Before conversion: "+d);  //fractional part lost  System.out.println("After conversion into long type: "+l);  //fractional part lost  System.out.println("After conversion into int type: "+i);  } } 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  Bitwise Operators  Logical Operators  Assignment Operators Arithmetic Operators  Arithmetic operators are used in mathematical expressions Operator Description Example + (Addition) Adds values on either side of the operator. A + B will give 30 Subtracts right-hand operand from left-hand - (Subtraction) operand. A - B will give -10 Multiplies values on either side of the * (Multiplication) operator. A * B will give 200 Divides left-hand operand by right-hand / (Division) operand. B / A will give 2 Divides left-hand operand by right-hand % (Modulus) operand and returns remainder. B % A will give 0 ++ (Increment) Increases the value of operand by 1. B++ gives 21 -- (Decrement) Decreases the value of operand by 1. B-- gives 19 Example -Arithmetic Operators  public class Test {  public static void main(String args[]) {  int a = 10;  int b = 20;  int c = 25;  int d = 25;  System.out.println("a + b = " + (a + b) );  System.out.println("a - b = " + (a - b) );  System.out.println("a * b = " + (a * b) );  System.out.println("b / a = " + (b / a) );  System.out.println("b % a = " + (b % a) );  System.out.println("c % a = " + (c % a) );  System.out.println("a++ = " + (a++) );  System.out.println("a-- = " + (a--) );  // Check the difference in d++ and ++d  System.out.println("d++ = " + (d++) );  System.out.println("++d = " + (++d) );  }} Relational Operators Operator Description Example Checks if the values of two operands are equal or not, if yes == (equal to) then condition becomes true. (A == B) is not true. Checks if the values of two operands are equal or not, if != (not equal to) values are not equal then condition becomes true. (A != B) is true. Checks if the value of left operand is greater than the value > (greater than) of right operand, if yes then condition becomes true. (A > B) is not true. Checks if the value of left operand is less than the value of < (less than) right operand, if yes then condition becomes true. (A < B) is true. Checks if the value of left operand is greater than or equal >= (greater than or equal to) to the value of right operand, if yes then condition becomes (A >= B) is not true. true. Checks if the value of left operand is less than or equal to b) );  System.out.println("a < b = " + (a < b) );  System.out.println("b >= a = " + (b >= a) );  System.out.println("b > 2 = " + c );  c = a >>> 2;  System.out.println("a >>> 2 = " + c );  }} Logical Operators Operator Description Example Called Logical AND operator. If both the operands are non-zero, then the condition && (logical and) becomes true. (A && B) is false Called Logical OR Operator. If any of the two operands are non-zero, then the condition || (logical or) becomes true. (A || B) is true Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition ! (logical not) is true then Logical NOT operator will make !(A && B) is true false. Assignment Operators Operator Description Example Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign value of A + = B into C Add AND assignment operator. It adds right operand to the left operand and assign the result to += left operand. C += A is equivalent to C = C + A Subtract AND assignment operator. It subtracts right operand from the left operand and assign -= the result to left operand. C -= A is equivalent to C = C – A Multiply AND assignment operator. It multiplies right operand with the left operand and assign *= the result to left operand. C *= A is equivalent to C = C * A /= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand. C /= A is equivalent to C = C / A Modulus AND assignment operator. It takes modulus using two operands and assign the result C %= A is equivalent to C = C % %= to left operand. A > 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2 Control Flow in Java  Java compiler executes the code from top to bottom. The statements in the code are executed according to the order in which they appear. However, Java provides statements that can be used to control the flow of Java code. Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of program. Control Flow in Java  Java provides three types of control flow statements.  Decision Making statements  ifstatements  switch statement  Loop statements  do while loop  while loop  for loop  for-each loop  Jump statements  break statement  continue statement Decision-Making statements:  1) If Statement:  In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted depending upon the specific condition. The condition of the If statement gives a Boolean value, either true or false. In Java, there are four types of if-statements.  Simple if statement  if-else statement  if-else-if ladder  Nested if-statement Simple if statement:  It is the most basic statement among all control flow statements in Java. It evaluates a Boolean expression and enables the program to enter a block of code if the expression evaluates to true.  Syntax of if statement :  if(condition) {  statement 1; //executes when condition is true  } Example Simple if statement  public class Student {  public static void main(String[] args) {  int x = 10;  int y = 12;  if(x+y > 20) {  System.out.println("x + y is greater than 20"); } } } if-else statement  The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.  Syntax:  if(condition) {  statement 1; //executes when condition is true  }  else{  statement 2; //executes when condition is false  } Example if-else statement  public class Student {  public static void main(String[] args) {  int x = 10;  int y = 12;  if(x+y < 10) {  System.out.println("x + y is less than 10");  } else {  System.out.println("x + y is greater than 20"); } } } if-else-if ladder  The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else statements that create a decision tree where the program may enter in the block of code where the condition is true. We can also define an else statement at the end of the chain.  Syntax of if-else-if statement  if(condition 1) {  statement 1; //executes when condition 1 is true  }  else if(condition 2) {  statement 2; //executes when condition 2 is true  }  else {  statement 2; //executes when all the conditions are false  }  Consider Example if-else-if ladder  public class Student {  public static void main(String[] args) {  String city = "Delhi";  if(city == "Meerut") {  System.out.println("city is meerut");  }else if (city == "Noida") {  System.out.println("city is noida");  }else if(city == "Agra") {  System.out.println("city is agra");  }else {  System.out.println(city);  }  } } Nested if-statement  In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if statement.  Syntax of Nested if-statement.  if(condition 1) {  statement 1; //executes when condition 1 is true  if(condition 2) {  statement 2; //executes when condition 2 is true  }  else{  statement 2; //executes when condition 2 is false  } } Example Nested if-statement  public class Student {  public static void main(String[] args) {  String address = "Delhi, India";   if(address.endsWith("India")) {  if(address.contains("Meerut")) {  System.out.println("Your city is Meerut");  }else if(address.contains("Noida")) {  System.out.println("Your city is Noida");  }else {  System.out.println(address.split(","));  }  }else {  System.out.println("You are not living in India");  } } } Switch Statement  Switch statements are similar to if-else-if statements. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched. The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.  switch (expression){  case value1:  statement1;  break; .  case valueN:  statementN;  break;  default:  default statement;  } Example Switch Statement  public class Student implements Cloneable {  public static void main(String[] args) {  int num = 2;  switch (num){  case 0:  System.out.println("number is 0");  break;  case 1:  System.out.println("number is 1");  break;  default:  System.out.println(num);  } } } Loop Statements  In programming, sometimes we need to execute the block of code repeatedly while some condition evaluates to true. However, loop statements are used to execute the set of instructions in a repeated order. The execution of the set of instructions depends upon a particular condition.  we have three types of loops that execute similarly. However, there are differences in their syntax and condition checking time.  for loop  while loop  do-while loop Java for loop  It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of code. We use the for loop only when we exactly know the number of times, we want to execute the block of code.  for(initialization, condition, increment/decrement) {  //block of statements } Example Java for loop  public class Calculattion {  public static void main(String[] args) {  // TODO Auto-generated method stub  int sum = 0;  for(int j = 1; j

Use Quizgecko on...
Browser
Browser