SlideShare a Scribd company logo
Java Introduction

Prepared by: Ragab Mustafa
Agenda
•   Overview of Programming Languages.
•   What’s and why Java.
•   What’s Eclipse .
•   Writing first program in Java.
•   Basics of java programming Language.
•   Variables, Operators and Types.
•   Methods, Conditionals and Loops.
Agenda cont.
•   Classes, Arrays and objects.
•   Solving a problems in Java.
•   Object-oriented Programming(OOP).
•   Inheritance.
Overview of Programming Languages.

• There are three types of programming
  languages:
 Machine Languages that encoded in 1’s and 0’s,
  that’s hard to write program in these languages.
 Low Level Languages(e.g. Assembly)it’s close to
  the machine code but not the same also it’s easer
  to write and read(understand).
 High Level Languages (e.g. C,C++,Java and
  C#)these      Languages needs a compiler to
  translate the program into machine code.
What’s Java
• Java is an OOP language developed at Sun
  Microsystems Labs by James Gosling at 1991.
• The first version called “OAK” but at 1995
  “Netscape” announced that Java would be
  incorporated into Netscape Navigator.
• Sun formally announced Java at a major
  conference in May 1995.
• it is also a good not only in “object-oriented
  programming “but also in “general programming
  language”.
Why Java
• Java has some advantages make it differ
  from the other languages as:
o   That it is platform independent(mean work well in the internet). It
    achieves this by using something called the ‘Java Virtual Machine’
    (JVM).




o   It’s a free source language.
Why Java cont.
• Also it’s
1. Simple Architecture       neutral .
2. Object oriented        Portable .
3. Distributed High     performance .
4. Multithreaded       Robust .
5. Dynamic        Secure.
What’s Eclipse
• Eclipse is a portable IDE for java it’s easy and
  powerful.
• There are more than one IDE for java as
  NetBeans, JBuilder and JDeveloper.
Prepare your PC and yourself!
• First you must download JDK from sun or go
  to here.
• Then run the IDE that you will treat with it
  here we will work by Eclipse.
• To download Eclipse IDE go to here or go to
  the home page of Eclipse .
• Just you download the IDE (hint: Eclipse is portable not installed)
  run it that will Explained by video.
The first program in java
• Write the program:
 public class FirstProgram
    {
 public static void main (String[] args)
    {
             System.out.print("Hello, 2 + 3 = ");
             System.out.println(5);
             System.out.println("Good Bye");
    }
 }
Basics of Java
• Program Structure
  class CLASSNAME {
  public static void main(String[] args)
      {
           STATEMENTS
      }
  }
Variables
• Named location that stores a value
• Form:
                 TYPE NAME;
• Example:
                 String fName;
  class Hello {
  public static void main(String[] arguments)
        {
        String fName = “ragab”;
        System.out.println(fName);
        fName = "Something else";
        System.out.println(fName);
        }
  }
Types
• Limits a variable to kinds of values
  String: plain text (“hello”)
  double: Floating-point, “real” valued
  number(3.14, -7.0)
   int: integer (5, -18)
     String fName = “hello”;
     double Pi = 3.14;
Types
• Order of Operations :Precedence like math, left
  to right.
  Right hand side of = evaluated first.
        double x= 20
        double x =3 / 2+ 1; // x= 2.0

• Conversion by casting
        Int a = 2; // a = 2
        double a = (double)2; // a = 2.0
        double a = 2/3; // a = 0.0
        double a = (double)2/3; // a = 0.6666…
        int a = (int)18.7; // a=18
Types
• Conversion by method:
  o Int to String:
     String five = Integer.toString(5);
     String five = “” + 5; // five = “5”
  o String to int:
     Int a=Integer.parseInt(“18”);
• Mathematical Functions:
  o Math.sin(x)
  o Math.cos(Math.PI / 2)
  o Math.log(Math.log(x + y))
Operators
•   Symbols that perform simple computations
•   Assignment: =
•   Addition: +
•   Subtraction: -
•   Multiplication: *
•   Division: /
Example
    class Math {
    public static void main(String[] arguments)
    {
    int score;
    score = 1 + 2 * 3;
    System.out.println(score);
    double copy = score;
    copy = copy / 2;
    System.out.println(copy);
    score = (int) copy;
    System.out.println(score);
    }
}
Methods
• Adding Methods
  public static void NAME() { STATEMENTS }
• To call a method:
  NAME();
• Parameters
  public static void NAME(TYPE NAME) { STATEMENTS }
• To call:
  NAME(EXPRESSION);
Methods
• Example:
  class Square {
    Public static void printSquare(int x){
    System.out.println(x*x);}
  public static void main(String[] arguments){
    int value = 2;
    printSquare(value);
    printSquare(3);
    printSquare(value*22);
     }
  }
Methods
• Multiple Parameters
     *…+ NAME(TYPE NAME, TYPE NAME) {STATEMENTS }
     NAME(arg1, arg2);
• Return Values
     public static TYPE NAME() {
     STATEMENTS
     return EXPRESSION;
      }
  void means “no type”
Conditionals
• if statement
      if (COMPARISON) {STATEMENTS }
• Example:
      class If {
         public static void test((int x)) {
         if (x > 5){
         System.out.println((x + " is > 5");
                  }
         }
      public static void main(String[] arguments){
          test(6);
          test(5);
         test(4);
         }
      }
Conditionals
• Comparison operators
  x > y: x is greater than y
  x< y: x is less than y
  x >= y: x is greater than or equal to y
  x <= y: x is less than or equal to y
  x == y: x equals y (assignment: =)
Conditionals
• else
         if (COMPARISON) {STATEMENTS
         } else {
         STATEMENTS
         }
• else if
         if (COMPARISON) {STATEMENTS
         } else if (COMPARISON) { STATEMENTS
         } else if (COMPARISON) { STATEMENTS
         }
         else {
         STATEMENTS
         }
Conditionals
• Example
   public static void test(int x){
   if (x > 5){
   System.out.println(x + " is > 5");}
    else if (x == 5){
   System.out.println(x + " equals 5");}
   else {
   System.out.println(x +”is < 5"); -
    }
   public static void main(String[] arguments){
    test(6);
   test(5);
    test(4);
   }
Loops
  static void main (String[] arguments) {
  System.out.println(“This is line 1”);
  System.out.println(“This is line 2”);
  System.out.println(“This is line 3”);
  }

• What if you want to do it for 200 lines?
• Loop operators allow to loop through a block
  of code.
• There are several loop operators in Java.
Loops
• The while operator:
     while (condition) {statement}
• Example:
     int i = 0;
     while (i < 3) {
     System.out.println(“This is line “ + i);
     i = i+1;}
• Count carefully
• Make sure that your loop has a chance to finish.
Loops
• The for operator:
      for (initialization;condition;update){statement}
• Example:
          int i;
          for (i = 0; i < 3; i=i++) {
          System.out.println (“This is line “ + i);}
• Embedded loops:
      for (int i = 0; i < 3; i++) {
      for (int j = 2; j < 4; j++){
      System.out.println (i + “ “ + j);
      } }
• Scope of the variable defined in the initialization:
  respective for block
Loops
• Branching Statements :
• break terminates a for or while loop
       for (int i=0; i<100; i++) {if(i ==
       terminationValue)
       break;
       else {...}
       }
• continue skips the current iteration of a for or while loop
  and proceeds directly to the next iteration
       for (int i=0; i<100; i++) {
       if(i == skipValue)
       continue;
       else {...}
       }
Arrays
• An array is an indexed list of values.
• You can make an array of int, of double, of
  String,etc.All elements of an array must have
  the same type.
   0    1   2   3              n-1



• This array contain n elements.
Arrays
• An array is noted using [] and is declared in the
  usual way:
      int values[]; // empty array
      int[] values; // equivalent declaration
• To create an array of a given size, use the
  operator new :
      int values[] = new int[5];
• or you may use a variable to specify the size:
      int size = 12;
      int values[] = new int[size];
Arrays
• Array Initialization:
• Curly braces can be used to initialize an array in
  the array declaration statement (and only there).
         int values[] = { 12, 24, -23, 47 };

• To access the elements of an array, use the []
  operator: values[index]
• Example:
         int values[] = { 12, 24, -23, 47 };
         values[3] = 18; // write
         int x = values[1] + 3; // read
Arrays
•   Each array has a length variable built-in that contains the length of the array.
                int values[] = new int[12];
                int size = values.length; // 12
•   Looping through an array
•   Example :
           int values[] = new int[5];
           for (int i=0; i<values.length; i++) {
           values[i] = i;
           int y = values[i] *values[i];
           System.out.println(y);
           }
•   Another one:
     double values[] = new double[25];
     int j=0;
     while (j<values.length) {...
     j++;
     }
Objects
• Objects are a collection of related data and
  methods.
• Example:
• Strings A string is a collection of characters
  (letters) and has a set of methods built in.
      String nextTrip = “Mexico”;
        int size = nextTrip.length(); // 6
Objects
• To create a new object, use the new operator.
  If you do not use new, you are making a
  reference to an object (i.e. a pointer to the
  same object).
        Point p;
        p.x = 23;
        p.y = -12;
        public static Point middlePoint (Point p1, Point p2) {
        Point q = new Point ((p1.x+p2.x)/2, (p1.y+p2.y)/2);
        return q; }
Classes
• A class is a prototype to design objects.
• It is a set of variables and methods that
  encapsulates the properties of the class of
  objects.
• In Java, you can (will) create several classes in
  project.
• A class constructor is called each time an
  object of the class is instantiated (created).
Packages
• A package is a set of classes that relate to a
  same purpose.
• Example: math, graphics, input/output...
• In order to use a package, you have to import
  it.                   package


    class               class              class



            object
Object Oriented Programming
• Objects are a collection of related data and
  methods.
• To create a new object, use the new operator.
  If you do not use new, you are making a
  reference to an object (i.e a pointer to the
  same object).
Objects and references
Point p1 = new Point (12,34);
Point p2 = p1;
System.out.println(“x = “ + p2.x); // 12
p1.x = 24;
System.out.println(“x = “ + p2.x); // 24!
The null object
• null simply represents no object. It is
  convenient
• as a return value to mean that a method failed
  for example. It may also be used to “remove”
  an element from an array.
  String values[] = { “ragab”, “ahmed”, “zidan” };
  values[1] = null;
Object methods v.s. class methods
     class Bicycle {
     static int gear, speed;
     public static void speedUp (Bicycle b) {
     b.speed += 10;}
     public static void main (String[] arguments) {
     Bicycle bike1 = new Bicycle();
     speedUp (bike1); }}

• static means that the variable is going to be same
  for all objects of the class.
• Class methods are declared static.
• static = the same for all objects
• nonstatic = different for each object
Abstraction
• Objects are tools for abstraction.
• Abstraction is a fundamental concept in
  computer science.
• In Java, objects are instances of a class.
• A class contains variables and methods that
  capture the essence of the object.
• An object is instantiated using new
Why is abstraction important?
• Modularity (allows to subdivide a big problem
  into smaller sub-problems)
• Powerful representation of real-world
  problems
Inheritance
• In the world, people inherit characteristics
  from their parents.
• In computer science, objects inherit variables
  and methods from their parents.
• When you define a class in Java, you may
  define it as a subclass of another class (its
  parent).
Why inheritance and it’s rules?
• Avoid duplicate code
• Improve modularity
            Inheritance rules
• The subclass inherits all variables and methods
• Use the extends keyword to indicate that one
  class inherits from another
• Use the super keyword in the subclass
  constructor to call the parent constructor
Modularity
Example
      public class Vehicle {
      public int nWheels; // number of wheels
      public Vehicle (int n)
      {nWheels = n;}
      int getNWheels ()
       {return nWheels;}}
• ----------------------------------------
      public class Car extends Vehicle {
      public Car (int n)
       {super (n);}
      public void openWindow() {}
      }
Example
      public class Bicycle extends Vehicle {
      public Bicycle (int n)
       {super (n);}
      public void freeStyle() {}
      }
• -------------------------------------
   public class World {
   public static void main (String[] args) {
   Bicycle bike = new Bike (2);
   Car car = new Car (4);
   System.out.println (“Car has “ +car.getNWheels() + “ wheels”);
   System.out.println (“Bike has “ +bike.getNWheels() + “ wheels”);--
OOP: Scope & Visibility
• Scope:
  – A variable cannot be used outside of
    the curly braces (“,...-”) in which it is declared.
  – E.g., Class-level variables (fields) are usable
    everywhere in the class; loop variables are only
    usable in the scope of the loop
OOP: Scope & Visibility
• Visibility:
  – public fields, methods, & constructors can be “seen”
    or used directly by all classes & subclasses
  – protected fields, methods, & constructors can only
    be seen or used from within their class or subclasses
  – private fields, methods, & constructors can only be
    seen or used from within their exact class (in general,
    most or all of a class’s fields should be private)
  – Fields, methods, and constructors with unspecified
    (“default” or “package”) visibility can be seen by
    some classes – more on this later
OOP: Getter & Setter Methods
•   Another way to access or modify fields
•   Good programming practice
•   Widely-used convention in Java
•   Also called accessors and mutators
•   Don’t come for free, but very useful when
    dealing with private or protected fields
OOP: Ecapsulation
• The Principle of Encapsulation
• Allows one to access and change the internals
  of a class, without having “direct access”
• Visibility, Accessors, & Mutators are vital tools
  for this OOP principle
OOP: this
• A way for an instance of class to refer to itself
   – E.g.: say Engineer has a field called trafficHours and a
     setter method with this signature:
   – public void setTrafficHours(int trafficHours);
   – How to resolve scope?
   – Solution: use this.trafficHours = trafficHours;
   – this does not work inside static methods

• Good programming practice
• Standard Java convention
• Does come for free, has many uses
Inheritance & Abstraction

• A class can extend another (single) class
• Subclasses inherit methods and variables from
  their parents
• This allows us to use objects to form an
  hierarchy of representations
• Classifications of objects and relationships
  between them can now be modeled!
Inheritance & Abstraction:The Object
               class
• Every class implicitly extends Object
• So, in Java, every object is an Object…
• “Class Object is the root of the class hierarchy.
  Every class has Object as a superclass. All
  objects, including arrays, implement the
  methods of this class.” – from the Java API
• Core and backbone of OOP in Java
• Methods of note are equals(Object) and
  toString() – more on these later
Inheritance & Abstraction:Overriding
           & Overloading

• What if we want a subclass’s inherited method
  to do something different than that of its
  parent? – Override it!
• What if we want multiple constructors for a
  class, or methods with the same name but
  different arguments? – Overload them!
Inheritance & Abstraction:Overriding
           & Overloading
• Overriding: re-defining an inherited method
• E.g., Say every Manager gets a weekly bonus
  of amount weeklyBonus (which would be
  defined somewhere in the class)
• To reflect this, we can override the
  weeklyPay() method simply by explicitly
  defining it again in Manager, with the desired
  changes
Inheritance & Abstraction:Overriding
           & Overloading

• Overloading: method or constructor with
  same name and type as another, but with a
  different signature (i.e., takes different
  number, ordering, or types of arguments)
• Cannot have methods with same name and
  arguments and different return type
Method Overriding
• Method overriding occurs when a subclass
  implements a method that is already implemented in a
  superclass. The method name must be the same, and
  the parameter and return types of the subclass's
  implementation must be subtypes of the superclass's
  implementation. You cannot allow less access than the
  access level of the superclass's method.
     eg,
     class Timer {
     public Date getDate(Country c) { ... } }
     class USATimer {
     public Date getDate(USA usa) { ... } }
Method Overloading

• Method overloading is when two methods
  share the same name but have a different
  number or type of parameters.
    eg,
    public void print(String str) { ...
    }
    public void print(Date date) { ...
    }
References
• Java how to program, book.
• Essential Java for scientists and Engineering,
  book.
• MIT Lectures.
• Tutorial from sun.
Java introduction

More Related Content

What's hot (20)

PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
Java generics
Hosein Zare
 
PDF
Java Day-6
People Strategists
 
PPTX
13. Java text processing
Intro C# Book
 
PPTX
11. Java Objects and classes
Intro C# Book
 
PPTX
07. Arrays
Intro C# Book
 
PDF
Java Day-5
People Strategists
 
PPTX
06.Loops
Intro C# Book
 
PPTX
02. Primitive Data Types and Variables
Intro C# Book
 
PPTX
19. Java data structures algorithms and complexity
Intro C# Book
 
PDF
Introduction to Python for Plone developers
Jim Roepcke
 
PPTX
13 Strings and Text Processing
Intro C# Book
 
PPTX
09. Java Methods
Intro C# Book
 
PDF
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
PDF
Java Day-7
People Strategists
 
PPTX
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
PPTX
Front end fundamentals session 1: javascript core
Web Zhao
 
PPTX
DSA 103 Object Oriented Programming :: Week 5
Ferdin Joe John Joseph PhD
 
PPTX
Java generics final
Akshay Chaudhari
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
Java generics
Hosein Zare
 
Java Day-6
People Strategists
 
13. Java text processing
Intro C# Book
 
11. Java Objects and classes
Intro C# Book
 
07. Arrays
Intro C# Book
 
Java Day-5
People Strategists
 
06.Loops
Intro C# Book
 
02. Primitive Data Types and Variables
Intro C# Book
 
19. Java data structures algorithms and complexity
Intro C# Book
 
Introduction to Python for Plone developers
Jim Roepcke
 
13 Strings and Text Processing
Intro C# Book
 
09. Java Methods
Intro C# Book
 
On Parameterised Types and Java Generics
Yann-Gaël Guéhéneuc
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Java Day-7
People Strategists
 
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Front end fundamentals session 1: javascript core
Web Zhao
 
DSA 103 Object Oriented Programming :: Week 5
Ferdin Joe John Joseph PhD
 
Java generics final
Akshay Chaudhari
 

Similar to Java introduction (20)

PPT
Learning Java 1 – Introduction
caswenson
 
PPTX
Java fundamentals
HCMUTE
 
PPT
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
PPT
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 
PPTX
Android webinar class_java_review
Edureka!
 
PPT
Java teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
PPT
Java Tutorial | My Heart
Bui Kiet
 
PPT
Javatut1
desaigeeta
 
PPT
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
PPT
Java tut1
Sumit Tambe
 
PPT
Java tut1
Sumit Tambe
 
PPT
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
PPT
Java Tutorial
ArnaldoCanelas
 
PPT
Java tutorial PPT
Intelligo Technologies
 
PPT
Java tutorial PPT
Intelligo Technologies
 
PPT
Tutorial java
Abdul Aziz
 
PPT
Java Tutorial
Vijay A Raj
 
PPT
Java tut1
Ajmal Khan
 
PPT
Java Tut1
guest5c8bd1
 
PPSX
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Learning Java 1 – Introduction
caswenson
 
Java fundamentals
HCMUTE
 
Java basic tutorial by sanjeevini india
Sanjeev Tripathi
 
Java basic tutorial by sanjeevini india
sanjeeviniindia1186
 
Android webinar class_java_review
Edureka!
 
Java teaching ppt for the freshers in colleeg.ppt
vvsofttechsolution
 
Java Tutorial | My Heart
Bui Kiet
 
Javatut1
desaigeeta
 
Java tut1 Coderdojo Cahersiveen
Graham Royce
 
Java tut1
Sumit Tambe
 
Java tut1
Sumit Tambe
 
Java_Tutorial_Introduction_to_Core_java.ppt
Govind Samleti
 
Java Tutorial
ArnaldoCanelas
 
Java tutorial PPT
Intelligo Technologies
 
Java tutorial PPT
Intelligo Technologies
 
Tutorial java
Abdul Aziz
 
Java Tutorial
Vijay A Raj
 
Java tut1
Ajmal Khan
 
Java Tut1
guest5c8bd1
 
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Ad

Recently uploaded (20)

PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPTX
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
PPT
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
The Different Types of Non-Experimental Research
Thelma Villaflores
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
PDF
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
PPTX
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Dimensions of Societal Planning in Commonism
StefanMz
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PPT-Q1-WEEK-3-SCIENCE-ERevised Matatag Grade 3.pptx
reijhongidayawan02
 
Talk on Critical Theory, Part One, Philosophy of Social Sciences
Soraj Hongladarom
 
Biological Bilingual Glossary Hindi and English Medium
World of Wisdom
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
The Different Types of Non-Experimental Research
Thelma Villaflores
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
Stokey: A Jewish Village by Rachel Kolsky
History of Stoke Newington
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
MENINGITIS: NURSING MANAGEMENT, BACTERIAL MENINGITIS, VIRAL MENINGITIS.pptx
PRADEEP ABOTHU
 
How to Set Up Tags in Odoo 18 - Odoo Slides
Celine George
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Dimensions of Societal Planning in Commonism
StefanMz
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Ad

Java introduction

  • 2. Agenda • Overview of Programming Languages. • What’s and why Java. • What’s Eclipse . • Writing first program in Java. • Basics of java programming Language. • Variables, Operators and Types. • Methods, Conditionals and Loops.
  • 3. Agenda cont. • Classes, Arrays and objects. • Solving a problems in Java. • Object-oriented Programming(OOP). • Inheritance.
  • 4. Overview of Programming Languages. • There are three types of programming languages:  Machine Languages that encoded in 1’s and 0’s, that’s hard to write program in these languages.  Low Level Languages(e.g. Assembly)it’s close to the machine code but not the same also it’s easer to write and read(understand).  High Level Languages (e.g. C,C++,Java and C#)these Languages needs a compiler to translate the program into machine code.
  • 5. What’s Java • Java is an OOP language developed at Sun Microsystems Labs by James Gosling at 1991. • The first version called “OAK” but at 1995 “Netscape” announced that Java would be incorporated into Netscape Navigator. • Sun formally announced Java at a major conference in May 1995. • it is also a good not only in “object-oriented programming “but also in “general programming language”.
  • 6. Why Java • Java has some advantages make it differ from the other languages as: o That it is platform independent(mean work well in the internet). It achieves this by using something called the ‘Java Virtual Machine’ (JVM). o It’s a free source language.
  • 7. Why Java cont. • Also it’s 1. Simple Architecture neutral . 2. Object oriented Portable . 3. Distributed High performance . 4. Multithreaded Robust . 5. Dynamic Secure.
  • 8. What’s Eclipse • Eclipse is a portable IDE for java it’s easy and powerful. • There are more than one IDE for java as NetBeans, JBuilder and JDeveloper.
  • 9. Prepare your PC and yourself! • First you must download JDK from sun or go to here. • Then run the IDE that you will treat with it here we will work by Eclipse. • To download Eclipse IDE go to here or go to the home page of Eclipse . • Just you download the IDE (hint: Eclipse is portable not installed) run it that will Explained by video.
  • 10. The first program in java • Write the program: public class FirstProgram { public static void main (String[] args) { System.out.print("Hello, 2 + 3 = "); System.out.println(5); System.out.println("Good Bye"); } }
  • 11. Basics of Java • Program Structure class CLASSNAME { public static void main(String[] args) { STATEMENTS } }
  • 12. Variables • Named location that stores a value • Form: TYPE NAME; • Example: String fName; class Hello { public static void main(String[] arguments) { String fName = “ragab”; System.out.println(fName); fName = "Something else"; System.out.println(fName); } }
  • 13. Types • Limits a variable to kinds of values String: plain text (“hello”) double: Floating-point, “real” valued number(3.14, -7.0) int: integer (5, -18) String fName = “hello”; double Pi = 3.14;
  • 14. Types • Order of Operations :Precedence like math, left to right. Right hand side of = evaluated first. double x= 20 double x =3 / 2+ 1; // x= 2.0 • Conversion by casting Int a = 2; // a = 2 double a = (double)2; // a = 2.0 double a = 2/3; // a = 0.0 double a = (double)2/3; // a = 0.6666… int a = (int)18.7; // a=18
  • 15. Types • Conversion by method: o Int to String: String five = Integer.toString(5); String five = “” + 5; // five = “5” o String to int: Int a=Integer.parseInt(“18”); • Mathematical Functions: o Math.sin(x) o Math.cos(Math.PI / 2) o Math.log(Math.log(x + y))
  • 16. Operators • Symbols that perform simple computations • Assignment: = • Addition: + • Subtraction: - • Multiplication: * • Division: /
  • 17. Example class Math { public static void main(String[] arguments) { int score; score = 1 + 2 * 3; System.out.println(score); double copy = score; copy = copy / 2; System.out.println(copy); score = (int) copy; System.out.println(score); } }
  • 18. Methods • Adding Methods public static void NAME() { STATEMENTS } • To call a method: NAME(); • Parameters public static void NAME(TYPE NAME) { STATEMENTS } • To call: NAME(EXPRESSION);
  • 19. Methods • Example: class Square { Public static void printSquare(int x){ System.out.println(x*x);} public static void main(String[] arguments){ int value = 2; printSquare(value); printSquare(3); printSquare(value*22); } }
  • 20. Methods • Multiple Parameters *…+ NAME(TYPE NAME, TYPE NAME) {STATEMENTS } NAME(arg1, arg2); • Return Values public static TYPE NAME() { STATEMENTS return EXPRESSION; } void means “no type”
  • 21. Conditionals • if statement if (COMPARISON) {STATEMENTS } • Example: class If { public static void test((int x)) { if (x > 5){ System.out.println((x + " is > 5"); } } public static void main(String[] arguments){ test(6); test(5); test(4); } }
  • 22. Conditionals • Comparison operators x > y: x is greater than y x< y: x is less than y x >= y: x is greater than or equal to y x <= y: x is less than or equal to y x == y: x equals y (assignment: =)
  • 23. Conditionals • else if (COMPARISON) {STATEMENTS } else { STATEMENTS } • else if if (COMPARISON) {STATEMENTS } else if (COMPARISON) { STATEMENTS } else if (COMPARISON) { STATEMENTS } else { STATEMENTS }
  • 24. Conditionals • Example public static void test(int x){ if (x > 5){ System.out.println(x + " is > 5");} else if (x == 5){ System.out.println(x + " equals 5");} else { System.out.println(x +”is < 5"); - } public static void main(String[] arguments){ test(6); test(5); test(4); }
  • 25. Loops static void main (String[] arguments) { System.out.println(“This is line 1”); System.out.println(“This is line 2”); System.out.println(“This is line 3”); } • What if you want to do it for 200 lines? • Loop operators allow to loop through a block of code. • There are several loop operators in Java.
  • 26. Loops • The while operator: while (condition) {statement} • Example: int i = 0; while (i < 3) { System.out.println(“This is line “ + i); i = i+1;} • Count carefully • Make sure that your loop has a chance to finish.
  • 27. Loops • The for operator: for (initialization;condition;update){statement} • Example: int i; for (i = 0; i < 3; i=i++) { System.out.println (“This is line “ + i);} • Embedded loops: for (int i = 0; i < 3; i++) { for (int j = 2; j < 4; j++){ System.out.println (i + “ “ + j); } } • Scope of the variable defined in the initialization: respective for block
  • 28. Loops • Branching Statements : • break terminates a for or while loop for (int i=0; i<100; i++) {if(i == terminationValue) break; else {...} } • continue skips the current iteration of a for or while loop and proceeds directly to the next iteration for (int i=0; i<100; i++) { if(i == skipValue) continue; else {...} }
  • 29. Arrays • An array is an indexed list of values. • You can make an array of int, of double, of String,etc.All elements of an array must have the same type. 0 1 2 3 n-1 • This array contain n elements.
  • 30. Arrays • An array is noted using [] and is declared in the usual way: int values[]; // empty array int[] values; // equivalent declaration • To create an array of a given size, use the operator new : int values[] = new int[5]; • or you may use a variable to specify the size: int size = 12; int values[] = new int[size];
  • 31. Arrays • Array Initialization: • Curly braces can be used to initialize an array in the array declaration statement (and only there). int values[] = { 12, 24, -23, 47 }; • To access the elements of an array, use the [] operator: values[index] • Example: int values[] = { 12, 24, -23, 47 }; values[3] = 18; // write int x = values[1] + 3; // read
  • 32. Arrays • Each array has a length variable built-in that contains the length of the array. int values[] = new int[12]; int size = values.length; // 12 • Looping through an array • Example : int values[] = new int[5]; for (int i=0; i<values.length; i++) { values[i] = i; int y = values[i] *values[i]; System.out.println(y); } • Another one: double values[] = new double[25]; int j=0; while (j<values.length) {... j++; }
  • 33. Objects • Objects are a collection of related data and methods. • Example: • Strings A string is a collection of characters (letters) and has a set of methods built in. String nextTrip = “Mexico”; int size = nextTrip.length(); // 6
  • 34. Objects • To create a new object, use the new operator. If you do not use new, you are making a reference to an object (i.e. a pointer to the same object). Point p; p.x = 23; p.y = -12; public static Point middlePoint (Point p1, Point p2) { Point q = new Point ((p1.x+p2.x)/2, (p1.y+p2.y)/2); return q; }
  • 35. Classes • A class is a prototype to design objects. • It is a set of variables and methods that encapsulates the properties of the class of objects. • In Java, you can (will) create several classes in project. • A class constructor is called each time an object of the class is instantiated (created).
  • 36. Packages • A package is a set of classes that relate to a same purpose. • Example: math, graphics, input/output... • In order to use a package, you have to import it. package class class class object
  • 37. Object Oriented Programming • Objects are a collection of related data and methods. • To create a new object, use the new operator. If you do not use new, you are making a reference to an object (i.e a pointer to the same object).
  • 38. Objects and references Point p1 = new Point (12,34); Point p2 = p1; System.out.println(“x = “ + p2.x); // 12 p1.x = 24; System.out.println(“x = “ + p2.x); // 24!
  • 39. The null object • null simply represents no object. It is convenient • as a return value to mean that a method failed for example. It may also be used to “remove” an element from an array. String values[] = { “ragab”, “ahmed”, “zidan” }; values[1] = null;
  • 40. Object methods v.s. class methods class Bicycle { static int gear, speed; public static void speedUp (Bicycle b) { b.speed += 10;} public static void main (String[] arguments) { Bicycle bike1 = new Bicycle(); speedUp (bike1); }} • static means that the variable is going to be same for all objects of the class. • Class methods are declared static. • static = the same for all objects • nonstatic = different for each object
  • 41. Abstraction • Objects are tools for abstraction. • Abstraction is a fundamental concept in computer science. • In Java, objects are instances of a class. • A class contains variables and methods that capture the essence of the object. • An object is instantiated using new
  • 42. Why is abstraction important? • Modularity (allows to subdivide a big problem into smaller sub-problems) • Powerful representation of real-world problems
  • 43. Inheritance • In the world, people inherit characteristics from their parents. • In computer science, objects inherit variables and methods from their parents. • When you define a class in Java, you may define it as a subclass of another class (its parent).
  • 44. Why inheritance and it’s rules? • Avoid duplicate code • Improve modularity Inheritance rules • The subclass inherits all variables and methods • Use the extends keyword to indicate that one class inherits from another • Use the super keyword in the subclass constructor to call the parent constructor
  • 46. Example public class Vehicle { public int nWheels; // number of wheels public Vehicle (int n) {nWheels = n;} int getNWheels () {return nWheels;}} • ---------------------------------------- public class Car extends Vehicle { public Car (int n) {super (n);} public void openWindow() {} }
  • 47. Example public class Bicycle extends Vehicle { public Bicycle (int n) {super (n);} public void freeStyle() {} } • ------------------------------------- public class World { public static void main (String[] args) { Bicycle bike = new Bike (2); Car car = new Car (4); System.out.println (“Car has “ +car.getNWheels() + “ wheels”); System.out.println (“Bike has “ +bike.getNWheels() + “ wheels”);--
  • 48. OOP: Scope & Visibility • Scope: – A variable cannot be used outside of the curly braces (“,...-”) in which it is declared. – E.g., Class-level variables (fields) are usable everywhere in the class; loop variables are only usable in the scope of the loop
  • 49. OOP: Scope & Visibility • Visibility: – public fields, methods, & constructors can be “seen” or used directly by all classes & subclasses – protected fields, methods, & constructors can only be seen or used from within their class or subclasses – private fields, methods, & constructors can only be seen or used from within their exact class (in general, most or all of a class’s fields should be private) – Fields, methods, and constructors with unspecified (“default” or “package”) visibility can be seen by some classes – more on this later
  • 50. OOP: Getter & Setter Methods • Another way to access or modify fields • Good programming practice • Widely-used convention in Java • Also called accessors and mutators • Don’t come for free, but very useful when dealing with private or protected fields
  • 51. OOP: Ecapsulation • The Principle of Encapsulation • Allows one to access and change the internals of a class, without having “direct access” • Visibility, Accessors, & Mutators are vital tools for this OOP principle
  • 52. OOP: this • A way for an instance of class to refer to itself – E.g.: say Engineer has a field called trafficHours and a setter method with this signature: – public void setTrafficHours(int trafficHours); – How to resolve scope? – Solution: use this.trafficHours = trafficHours; – this does not work inside static methods • Good programming practice • Standard Java convention • Does come for free, has many uses
  • 53. Inheritance & Abstraction • A class can extend another (single) class • Subclasses inherit methods and variables from their parents • This allows us to use objects to form an hierarchy of representations • Classifications of objects and relationships between them can now be modeled!
  • 54. Inheritance & Abstraction:The Object class • Every class implicitly extends Object • So, in Java, every object is an Object… • “Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.” – from the Java API • Core and backbone of OOP in Java • Methods of note are equals(Object) and toString() – more on these later
  • 55. Inheritance & Abstraction:Overriding & Overloading • What if we want a subclass’s inherited method to do something different than that of its parent? – Override it! • What if we want multiple constructors for a class, or methods with the same name but different arguments? – Overload them!
  • 56. Inheritance & Abstraction:Overriding & Overloading • Overriding: re-defining an inherited method • E.g., Say every Manager gets a weekly bonus of amount weeklyBonus (which would be defined somewhere in the class) • To reflect this, we can override the weeklyPay() method simply by explicitly defining it again in Manager, with the desired changes
  • 57. Inheritance & Abstraction:Overriding & Overloading • Overloading: method or constructor with same name and type as another, but with a different signature (i.e., takes different number, ordering, or types of arguments) • Cannot have methods with same name and arguments and different return type
  • 58. Method Overriding • Method overriding occurs when a subclass implements a method that is already implemented in a superclass. The method name must be the same, and the parameter and return types of the subclass's implementation must be subtypes of the superclass's implementation. You cannot allow less access than the access level of the superclass's method. eg, class Timer { public Date getDate(Country c) { ... } } class USATimer { public Date getDate(USA usa) { ... } }
  • 59. Method Overloading • Method overloading is when two methods share the same name but have a different number or type of parameters. eg, public void print(String str) { ... } public void print(Date date) { ... }
  • 60. References • Java how to program, book. • Essential Java for scientists and Engineering, book. • MIT Lectures. • Tutorial from sun.