SlideShare une entreprise Scribd logo
1  sur  77
Chapter 1
Introduction
Java’s
Major Advantage
 over C & C++
Because pointers were a major source of
bugs in C and C++, Gosling omitted
pointers entirely from Java.

• Actually, pointers are still an important
part of the language--all objects are
referenced by pointers--but the language
handles them, not the programmer.
Java’s Origins in C & C++
Thus, it has been said that...

     “Java is C without the Guns and Knives.”
Java Architecture
• By now, Java itself has matured into its
3rd version, named Java 2. This course is
based on Java 2. The most current is Java
2 (1.5.1)
• Java is Object-Oriented--that means
everything in the language behaves like
an object.
• What exactly that means will be
explained in the coming weeks.
Java Architecture
Java’s Architecture comes from four separate
but intertwined technologies:
• the Java Programming Language
• the Java class file format
• the Java API, or Application Programming Interface
• the Java Virtual Machine
Java Architecture
Source programs are written in the Java Programming
Language.

All procedural code falls within methods.

Programs are compiled into Java class files.

Classes run in the Java Virtual Machine.
Java Architecture
• When a Java program runs, it is assisted by
other classes in the Java the Application
Programming Interface, or API.
Java Architecture
      Combined, the Java      Example Java API class files
    Virtual MachineObject.class
                     and the                String.class
         Java API form a
           “Platform.”
    Compile-Time
    Environment

     Hello.class

                                              Java
                                             Virtual
   Java Compiler
                                             Machine
                                            Run-Time Environment
    Hello.java
Java Architecture


• The Java Platform is unique, because it
can work without modification
     on any platform,
     on any operating system,
     if that platform has a
     “Java Virtual Machine.”
Java Architecture
                       Java
     What is the      Virtual      ?
                      Machine

Comparison of a typical Procedural
Program with a Java Program:
• In a typical C program, the source code is
compiled into a native machine language
module that consists of 1’s and 0’s.
C Source Code



           C object module
            compiled into
           machine language

• The machine language is specifically tailored
to one OS, be it Wintel, Mac, UNIX or MVS. •
Therefore, it is impossible for one object
module to be portable between platforms.
Java Architecture
         Java “bytecode”
In contrast to conventional programming
languages, a Java program is not compiled
into native machine language.
• Instead, Java makes bytecode.
• Bytecode is the result of a “compile”, but
the compile results in an intermediate form
that stops short of native machine-specific
code.
Java Architecture

• Instead of making a machine language
native code for each particular OS, Java
makes a single, universal bytecode module
that feeds into any Java Virtual Machine
(JVM).

• Each OS has its own different
implementation of the Java Virtual Machine.
Java Architecture

• The JVM sets up its own world within
your RAM.

• The JVM creates an internal
software-only sub-computer within the OS.

• The bytecode talks to the JVM, and the
JVM talks to the Operating System.
Java Architecture

• Thus, you get the Holy Grail of software reuse:



          “Write Once,
         Run Anywhere”.
Java Source

The            You can easily see why Bill
bytecode      Gates isn’t in love with Java!
is met
half-way
by the
JVM.


  JVM-Win      JVM-Mac     JVM-Unix     JVM-IBM
Java Architecture

  • The Virtual Machine interprets the
  bytecode one instruction at a time,
  and translates it into native machine
  code.

  • You compile your program once
  into bytecode, but it is interpreted
  anew every time it runs.
Security and the “Sandbox
C and C++ are famous for speed.

     • One reason they are fast is because C
and C++ don’t do things like checking the
bounds of arrays.                   • In C or
C++, a program can walk off the edge of an
array and invade the memory space beyond.
     • Hackers love that about C and C++.
Security and the “Sandbox”
• Another weakness of C/C++, that is a
favorite among Hackers, is the Buffer
Overflow.

• In this attack, the Hacker floods too much
data into a buffer and whatever overflows it
is turned loose on the system.

• Java solves these problems
Security and the “Sandbox”
• How Java Combats malicious code:
     Java checks array boundaries
     Java halts Buffer Overflows
     Java has Garbage collection to get
    rid of objects that are no longer
    used.
     Java’s compiler checks to make
    sure the code is safe before it runs.
• Gosling built security into Java, using a
    concept known as the “Sandbox.”
Security and the “Sandbox”
                   Local Code

    All Code, both Local and Remote, Must Pass Security Policy

         JDK 1.2                     Security Model

                                              SANDBOX




                               Vulnerable System Resources
                       (files, etc) Even Local Code is Not Trusted
Security and the “Sandbox”
• 5 Steps To Writing A Java Program:
     1.) Write it in a Text Editor
     2.) Compiler creates bytecode
     3.) The “Class loader” places the .
          class file in memory.
     4.) The “Bytecode Verifier” makes sure
     the code adheres to Java’s
        security rules.
     5.) The JVM Interpreter reads
        bytecode and makes platform
        native code.
Security and the “Sandbox”
• You see, preventing problems is a major
design consideration in Java.

• This idea led to the most import aspect of
Java: Object Orientation.

• Object Orientation protects data and lets a
program do only what is explicitly permitted.

• You could say Java is pessimistic.
Objects in Java

• In Java, Object Orientation is so
pervasive that it’s nearly impossible
to write a strictly procedural program
in the language.
Objects in Java

• Objects are reusable components.

• In Java, everything must be run from a
“class” file. This “class” contains bytecode.

• Java source code has the extension
Xxx.java
Objects in Java

• If I write a Java program called:

     Hello.java

     then, when compiled, this program will
be called:

     Hello.class
Objects in Java
• A class object is compiled Java code that
contains its own data variables, called
members, and sections of procedural code
called methods.

    If you have programmed in COBOL, a
method is like a paragraph you perform.

    If you have programmed in C or C++, a
method is like a function your program calls.
Objects in Java

• The combination of the data variables
         and the methods
                  that are used to read,
                                   write
                              or modify
                        those variables

is called a class.
Objects in Java

• Java has a rich collection of Class Libraries.

• These are also known as the Java API or
Application Programming Interface.

• To program in Java, you must

     i.) Learn the Language, and
     ii.) Learn the Class Libraries.
Objects in Java

• These class libraries greatly simplify your
job as a Java programmer.

• They help you to write complex
programs quickly.

• To master Java, you must master these
class libraries.
Compiling A Java Program
• You have created a Java program called
      Hello.java
• To compile it, you run the JDK supplied
utility called:
                javac
C:javac Hello.java
    If this was successful, a file called:
  Hello.class will be produced.
First Java Program
• The two largest varieties of Java
programs:

     Applications

     Applets
First Java Program

• A Java Application is a free-standing
program that is capable of running
directly in the Java Virtual Machine.

• A Java Applet is a mini-program that is
much more limited in its abilities. An
Applet can only run within the context of
an HTML browser.
First Java Program

• A Java Application is a free-standing
program that is capable of running
directly in the Java Virtual Machine.

• A Java Applet is a mini-program that is
much more limited in its abilities. An
Applet can only run within the context of
an HTML browser.
A Java Application
// HelloWorld.java Our first Java Application

public class HelloWorld
{
       public static void main( String args[])
       {
              System.out.println( “Hello World!” );
       }
}

Now our Application is complete. We have added the method “main”.
All methods are lower case. main is a special method--it actually runs
the program.
         In any application, you are always guaranteed that method
main will run.
C:>javac HelloWorld.java

  C:>


• A successful compile of your java
program will return to a bare cursor, as
you see here.
A Java Application
  C:>javac HelloWorld.java

  C:>java HelloWorld
  Hello World!

     • To run your compiled Application,
you enter lowercase java HelloWorld
on the command line.         • Notice, the
“.class” extension is omitted.
Now load the JDK1.4.1,
the documentation,
change the class path and
write your first Java program.
Chapter 2
Introduction to Java
    Applications
Java Applications Are
         A Series of Classes
• A Java Application must have the method
main.
• A Java Application begins executing at
main.
• Let’s look at details of an Application:
public class Welcome1
 {
        public static void main( String args[] )
        {
               System.out.println( “Welcome to Java!” );

        } // end of main()
 } // end of class Welcome1


• This is a basic Application.
• Notice the comments. These are required in this course.
Java is free form, but you’ll be happy if you get in the habit
of documenting like this.
• Also, whenever you type an opening curly bracket, type
the closing one right away.
• Your curly brackets must always--in this class--line up as
shown.
public class Welcome1
 {
        public static void main( String args[] )
        {
               System.out.println( “Welcome to Java!” );

        } // end of main()
 } // end of class Welcome1

• The line above in blue is the class definition for Welcome1.
• Every class name must be Capitalized.
• Notice, every scrap of code is within this class.
• Since it is named Welcome1, this Application is saved in a file
called Welcome1.java, spelled exactly the same.
• The compiler will make a file called Welcome1.class.
public class Welcome1
{
       public static void main( String args[] )
       {
              System.out.println( “Welcome to Java!” );

       } // end of main()
} // end of class Welcome1


• The word Welcome1 is an identifier.
• An identifier is a user-defined word, which consists of:
       letters
       digits
       _ (underscore)
       $ (a dollar sign)
• An identifier cannot begin with a digit.
public class Welcome1
{
       public static void main( String args[] )
       {
              System.out.println( “Welcome to Java!” );

       } // end of main()
} // end of class Welcome1


• Notice that we put the word public before the word
class.
• This means the class can be called by anything.
• The alternatives to public are discussed in Chapter 8.
public class Welcome1
{
       public static void main( String args[] )
       {
              System.out.println( “Welcome to Java!” );

       } // end of main()
} // end of class Welcome1


• The method main is also declared public.
• This should just be copied until Chapter 6, when we
know methods better.
public class Welcome1
{
       public static void main( String args[] )
       {
              System.out.println( “Welcome to Java!” );

       } // end of main()
} // end of class Welcome1


• void means nothing is returned to the operating
system when the program finishes.
• The ( String args[] ) works with “arguments”
that were passed when the program was executed.
• Although you cannot omit it ( String args[] ),
we don’t discuss this topic just yet, so please copy it.
public class Welcome1
  {
         public static void main( String args[] )
         {
                System.out.println( “Welcome to Java!” );

         } // end of main()
  } // end of class Welcome1

• The System.out.println puts the message in
quotes on the command console.
• If we used System.out.print, then the cursor
would not do a carriage return / line the after it prints the
                     This is called feed
text.                Standard output
                           object.
• Notice the opening and closing blue curly brackets. The
unit of code enclosed in them is called a “block.”
• It is also called the “body” of the method.
public class Welcome1
{
       public static void main( String args[] )
       {
             System.out.println( “Welcome to Java!” );

       } // end of main()
} // end of class Welcome1

 • You will find that you very rarely use this
 Standard output object.
 • Instead, you will use the GUI objects.

 • Notice in red the semicolon. ; All executable
 statements in Java ends in a semicolon.
public class Welcome1
{
       public static void main( String args[] )
       {
              System.out.print( “Welcome ” );
              System.out.println( “to Java!” );

       } // end of main()
} // end of class Welcome1


• This will still produce the same text as the
previous version.
public class Welcome1
{
       public static void main( String args[] )
       {
              System.out.print( “WelcomentonJava! ” );
       } // end of main()
} // end of class Welcome1


• Notice the “ n ”. The slash is an escape
character. It tells the System object that whatever
follows the slash is special:
n    new line
      t tab
      r carriage return        Welcome                   to
                                                      Java!
       backslash
      ” quote
Primitive Data Types
• A variable called number1 actually refers to a place in
memory where the value of the variable is stored.
• Every variable in Java has a:
      name,
      type,
      size, and a
      value.
Primitive Data Types
      name

Variable names must conform to the rules for identifiers:

      • they must begin with a letter,

      • after that they can contain digits, dollar signs
       and underscores.

      • Java uses Unicode for its characters, so any
         “letter” that is valid for a word in any world
       language is therefore valid for a name in
      Java.
Primitive Data Types
      type
• The “type” appears before the identifier name.
• The type can be one of the “primitive data types” or it
can be any previously defined class.

    int num1;
                      • You declare a variable and initialize it on
                      the same line.
    num1 = 2;

                      • This is a declaration. At this point, the
                      name num1 refers to a location {a
                      pointer} in the computer’s RAM where
                      this variable is stored.
    int num1=2;
                      • Because an int is declared, we know
                      that four bytes are set aside.
                       • Still, nothing is stored in it yet.
Primitive Data Types
     size
       • When we assign a type [ int, String] to a
variable, we are not only declaring a memory
location.
      • We also decide how big of a number or
      character is able to be stored in that variable.
Primitive Data Types
    value
    • Finally, the value is what we want the
     variable to store.
Primitive Data Types
• Java is a Strongly-typed language. That
means, every variable must be declared as a type.
       In Java, there are 8 primitive types:

• 6 of those refer to numbers
       --4 for integers types,
       --2 for floating-point types,

• 1 is the character type char, used for characters
in Unicode encoding, and

• 1 is a boolean type for true or false
  values.
Primitive Data Types
    int
    • In contrast to C/C++, an int will always--no
    matter which operating system--take 4 bytes
    of storage space.
    • Because those 4 bytes are set in stone, you can be
            sure that every JVM that runs your program
    will be able to store the same size numbers.
     • int is the most commonly used number size.
    Range:
    -2,147,483,648 to 2,147,483,647 (over two billion)
Primitive Data Types
     short
      • In Java, a short is defined as 2 bytes, no
      matter which operating system is used.
       • You would only use this for special situations,
such as when speed is really crucial.
             { For VB programmers, a short is what
             you’ve come to think of as an int . }
      Range:
      -32,768 to 32,767
Primitive Data Types
     long
      • A long is defined as 8 bytes, no matter
which operating system is used.
      Range:
      -9,223,372,036,854,775,808L to


      9,223,372,036,854,775,807L
  • Hexadecimal numbers have a prefix: 0x
        0x1CFE.
  • Please notice the upper-case L suffix is appended to any
  long. This is required.
Primitive Data Types
 byte
  • A byte is defined as 1 byte, no matter
  which operating system is used.
  Range:
  -128 to 127


• Again, like a short, a byte is only used under
rare circumstances.
Primitive Data Types
 float
  • A float is defined as 4 bytes, no matter
  which operating system is used.
  Range:
  approximately 3.40282347E+38F
        ( 6-7 significant decimal digits )

• Because there are so few decimal places available,
float is not used all that often.
Primitive Data Types
    double
   • A double is defined as 8 bytes, no matter
         which operating system is used.
   Range:
   approximately 1.79769313486231570E+308
         ( 15 significant decimal digits )
   • “double is the one to have when you’re having more
   than one--decimal place, that is.”
   • This is the most common choice for any decimal.
   • double is the default, not float, therefore, no special
   character is appended. (See red arrow.)
Primitive Data Types
       char
       • A char is defined as 2 bytes, no matter which    operating
system is used. A char type always
     refers to a character in the Unicode encoding
     scheme. [uFFFF u is the escape character syntax]   About
65,536 different characters can be
     represented.
       • Single quotes denote a char constant

       „H‟    is a char constant

       “H”    is a string that happens to only contain
       a             single character.
Primitive Data Types
       char
       • A char is defined as 2 bytes. A char type is a         single
Unicode character.                                 [uFFFF u is the
escape character syntax--65,536     different characters can be
represented.]
       • Single quotes denote a single-letter char constant
       „H‟    is a char constant.
       “H” is a String that happens to only contain a
       single character--it is not a char.                      This
is a syntax error! The compiler will              complain.
Primitive Data Types
 boolean
 • A boolean type has only two values.
 • In contrast to C/C++, in Java 0 and 1 cannot
        stand in for true or false.
 • A boolean type must be assigned the value of
  the constants true or false.
      [Meaning, these exact lowercase words.]
Java Math Operators
• Addition         +
• Subtraction      -
• Multiplication   *
• Division         /
• Modulus          %
All are binary operators, i.e., they work with two
numbers. They are executed according to the rules
for operator precedence. [page 1240]
  (There is no operator for exponentiation in Java)
Java Math Operators

• Multiplication         *
• What happens if you multiply variables of different types?
  int x = 2;
  double y = 3.889, sum = 0.000;
  sum = y * x;



• The integer will be temporarily converted to a
double and two doubles will be multiplied.
• Afterwards, the original integer is unchanged.
Java Math Operators
• Rules for Temporary Conversions
1st Priority: If either of the operands is of type double, then the other one is converted to
double for the calculation.
2nd Priority: Otherwise, if either of the operands is of type float, then the other one is
converted to float for the calculation.
3rd Priority: Otherwise, if any of the operands is of type long, then the other one is
converted to long for the calculation.


Note: these conversions are automatic because none of them result in a loss of accuracy.
Java Math Operators
• Static Casts
So, what happens when you desire to convert a double to
a float? Information will inevitably be lost.
         • You accomplish this using a cast.
  int x = 2, sum = 0;
  double y = 3.889;
  sum = (int)y * x;
  { sum is now equal to 6 }



 • Here, a value of just 3 will be used for y.
 • If you want to round y, you a method from class
 Math:
             sum = (int)Math.round(y) * x;
Java Math Operators

• Division         /
• Division can lead to unexpected results:
If both operands are integers, then the result of the
division is also an integer.
Any fractional part of the division is discarded.

Therefore:          17/3 = 5
Java Math Operators

• Modulus                %
• The modulus operator is confusing at first, but
eventually it becomes your good friend.
In contrast to the division operator, it returns the
remainder of any division. The modulus operator can
only be used when both operands are integers.

      17 % 3 = 2
You say this “17 modulus 3 equals 2”
Comparison Operators
• These are used for selection
structures:
equality                 ==
not equal                !=
greater than             >
less than                <
greater than or equal    >=
less than or equal       <=
Comparison Operators

• The equality operator is a common source of mistakes:

equality                  ==
Note that two equal signs are always used.
The single equal sign     [      =     ] is only used for
assignment, that is, assigning the value on the right to the
variable on the left.
             num1 = 33;
Comparison Operators

• When you make a compound symbol using the equal
sign, the equal sign is always on the right:



equality                ==
not equal               !=
greater than or equal   >=
less than or equal      <=

Contenu connexe

Tendances (20)

Java Programming
Java ProgrammingJava Programming
Java Programming
 
Core java slides
Core java slidesCore java slides
Core java slides
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Java basics
Java basicsJava basics
Java basics
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVA
 
Programming in Java
Programming in JavaProgramming in Java
Programming in Java
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Java notes
Java notesJava notes
Java notes
 
Core java course syllabus
Core java course syllabusCore java course syllabus
Core java course syllabus
 
Java for Recruiters
Java for RecruitersJava for Recruiters
Java for Recruiters
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Chapter 1 introduction to java technology
Chapter 1 introduction to java technologyChapter 1 introduction to java technology
Chapter 1 introduction to java technology
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Java unit 1
Java unit 1Java unit 1
Java unit 1
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
Java basics notes
Java basics notesJava basics notes
Java basics notes
 

Similaire à basic core java up to operator

Similaire à basic core java up to operator (20)

1 java introduction
1 java introduction1 java introduction
1 java introduction
 
1 java intro
1 java intro1 java intro
1 java intro
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptxJAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
JAVA PROGRAM CONSTRUCTS OR LANGUAGE BASICS.pptx
 
Java1
Java1Java1
Java1
 
Java1
Java1Java1
Java1
 
Java introduction
Java introductionJava introduction
Java introduction
 
1 Module 1 Introduction.pptx
1 Module 1 Introduction.pptx1 Module 1 Introduction.pptx
1 Module 1 Introduction.pptx
 
1.Intro--Why Java.pptx
1.Intro--Why Java.pptx1.Intro--Why Java.pptx
1.Intro--Why Java.pptx
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
1. JAVA_Module_1-edited - AJIN ABRAHAM.pptx.pdf
 
Lec 1-of-oop2
Lec 1-of-oop2Lec 1-of-oop2
Lec 1-of-oop2
 
unit1.pptx
unit1.pptxunit1.pptx
unit1.pptx
 
Lec 3 01_aug13
Lec 3 01_aug13Lec 3 01_aug13
Lec 3 01_aug13
 
JavaClassPresentation
JavaClassPresentationJavaClassPresentation
JavaClassPresentation
 
Lesson1 intro
Lesson1 introLesson1 intro
Lesson1 intro
 
Lesson1 intro
Lesson1 introLesson1 intro
Lesson1 intro
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptxJAVA_Day1_BasicIntroduction.pptx
JAVA_Day1_BasicIntroduction.pptx
 
JAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptxJAVAPart1_BasicIntroduction.pptx
JAVAPart1_BasicIntroduction.pptx
 

Plus de kamal kotecha

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with codekamal kotecha
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of javakamal kotecha
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 

Plus de kamal kotecha (20)

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Java rmi example program with code
Java rmi example program with codeJava rmi example program with code
Java rmi example program with code
 
Java rmi
Java rmiJava rmi
Java rmi
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Jdbc api
Jdbc apiJdbc api
Jdbc api
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
JSP Error handling
JSP Error handlingJSP Error handling
JSP Error handling
 
Jsp element
Jsp elementJsp element
Jsp element
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Packages and inbuilt classes of java
Packages and inbuilt classes of javaPackages and inbuilt classes of java
Packages and inbuilt classes of java
 
Interface
InterfaceInterface
Interface
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Class method
Class methodClass method
Class method
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Control statements
Control statementsControl statements
Control statements
 

Dernier

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 

Dernier (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 

basic core java up to operator

  • 1.
  • 4. Because pointers were a major source of bugs in C and C++, Gosling omitted pointers entirely from Java. • Actually, pointers are still an important part of the language--all objects are referenced by pointers--but the language handles them, not the programmer.
  • 5. Java’s Origins in C & C++ Thus, it has been said that... “Java is C without the Guns and Knives.”
  • 6. Java Architecture • By now, Java itself has matured into its 3rd version, named Java 2. This course is based on Java 2. The most current is Java 2 (1.5.1) • Java is Object-Oriented--that means everything in the language behaves like an object. • What exactly that means will be explained in the coming weeks.
  • 7. Java Architecture Java’s Architecture comes from four separate but intertwined technologies: • the Java Programming Language • the Java class file format • the Java API, or Application Programming Interface • the Java Virtual Machine
  • 8. Java Architecture Source programs are written in the Java Programming Language. All procedural code falls within methods. Programs are compiled into Java class files. Classes run in the Java Virtual Machine.
  • 9. Java Architecture • When a Java program runs, it is assisted by other classes in the Java the Application Programming Interface, or API.
  • 10. Java Architecture Combined, the Java Example Java API class files Virtual MachineObject.class and the String.class Java API form a “Platform.” Compile-Time Environment Hello.class Java Virtual Java Compiler Machine Run-Time Environment Hello.java
  • 11. Java Architecture • The Java Platform is unique, because it can work without modification on any platform, on any operating system, if that platform has a “Java Virtual Machine.”
  • 12. Java Architecture Java What is the Virtual ? Machine Comparison of a typical Procedural Program with a Java Program: • In a typical C program, the source code is compiled into a native machine language module that consists of 1’s and 0’s.
  • 13. C Source Code C object module compiled into machine language • The machine language is specifically tailored to one OS, be it Wintel, Mac, UNIX or MVS. • Therefore, it is impossible for one object module to be portable between platforms.
  • 14. Java Architecture Java “bytecode” In contrast to conventional programming languages, a Java program is not compiled into native machine language. • Instead, Java makes bytecode. • Bytecode is the result of a “compile”, but the compile results in an intermediate form that stops short of native machine-specific code.
  • 15. Java Architecture • Instead of making a machine language native code for each particular OS, Java makes a single, universal bytecode module that feeds into any Java Virtual Machine (JVM). • Each OS has its own different implementation of the Java Virtual Machine.
  • 16. Java Architecture • The JVM sets up its own world within your RAM. • The JVM creates an internal software-only sub-computer within the OS. • The bytecode talks to the JVM, and the JVM talks to the Operating System.
  • 17. Java Architecture • Thus, you get the Holy Grail of software reuse: “Write Once, Run Anywhere”.
  • 18. Java Source The You can easily see why Bill bytecode Gates isn’t in love with Java! is met half-way by the JVM. JVM-Win JVM-Mac JVM-Unix JVM-IBM
  • 19. Java Architecture • The Virtual Machine interprets the bytecode one instruction at a time, and translates it into native machine code. • You compile your program once into bytecode, but it is interpreted anew every time it runs.
  • 20. Security and the “Sandbox
  • 21. C and C++ are famous for speed. • One reason they are fast is because C and C++ don’t do things like checking the bounds of arrays. • In C or C++, a program can walk off the edge of an array and invade the memory space beyond. • Hackers love that about C and C++.
  • 22. Security and the “Sandbox” • Another weakness of C/C++, that is a favorite among Hackers, is the Buffer Overflow. • In this attack, the Hacker floods too much data into a buffer and whatever overflows it is turned loose on the system. • Java solves these problems
  • 23. Security and the “Sandbox” • How Java Combats malicious code: Java checks array boundaries Java halts Buffer Overflows Java has Garbage collection to get rid of objects that are no longer used. Java’s compiler checks to make sure the code is safe before it runs. • Gosling built security into Java, using a concept known as the “Sandbox.”
  • 24. Security and the “Sandbox” Local Code All Code, both Local and Remote, Must Pass Security Policy JDK 1.2 Security Model SANDBOX Vulnerable System Resources (files, etc) Even Local Code is Not Trusted
  • 25. Security and the “Sandbox” • 5 Steps To Writing A Java Program: 1.) Write it in a Text Editor 2.) Compiler creates bytecode 3.) The “Class loader” places the . class file in memory. 4.) The “Bytecode Verifier” makes sure the code adheres to Java’s security rules. 5.) The JVM Interpreter reads bytecode and makes platform native code.
  • 26. Security and the “Sandbox” • You see, preventing problems is a major design consideration in Java. • This idea led to the most import aspect of Java: Object Orientation. • Object Orientation protects data and lets a program do only what is explicitly permitted. • You could say Java is pessimistic.
  • 27. Objects in Java • In Java, Object Orientation is so pervasive that it’s nearly impossible to write a strictly procedural program in the language.
  • 28. Objects in Java • Objects are reusable components. • In Java, everything must be run from a “class” file. This “class” contains bytecode. • Java source code has the extension Xxx.java
  • 29. Objects in Java • If I write a Java program called: Hello.java then, when compiled, this program will be called: Hello.class
  • 30. Objects in Java • A class object is compiled Java code that contains its own data variables, called members, and sections of procedural code called methods. If you have programmed in COBOL, a method is like a paragraph you perform. If you have programmed in C or C++, a method is like a function your program calls.
  • 31. Objects in Java • The combination of the data variables and the methods that are used to read, write or modify those variables is called a class.
  • 32. Objects in Java • Java has a rich collection of Class Libraries. • These are also known as the Java API or Application Programming Interface. • To program in Java, you must i.) Learn the Language, and ii.) Learn the Class Libraries.
  • 33. Objects in Java • These class libraries greatly simplify your job as a Java programmer. • They help you to write complex programs quickly. • To master Java, you must master these class libraries.
  • 34. Compiling A Java Program • You have created a Java program called Hello.java • To compile it, you run the JDK supplied utility called: javac C:javac Hello.java If this was successful, a file called: Hello.class will be produced.
  • 35. First Java Program • The two largest varieties of Java programs: Applications Applets
  • 36. First Java Program • A Java Application is a free-standing program that is capable of running directly in the Java Virtual Machine. • A Java Applet is a mini-program that is much more limited in its abilities. An Applet can only run within the context of an HTML browser.
  • 37. First Java Program • A Java Application is a free-standing program that is capable of running directly in the Java Virtual Machine. • A Java Applet is a mini-program that is much more limited in its abilities. An Applet can only run within the context of an HTML browser.
  • 38. A Java Application // HelloWorld.java Our first Java Application public class HelloWorld { public static void main( String args[]) { System.out.println( “Hello World!” ); } } Now our Application is complete. We have added the method “main”. All methods are lower case. main is a special method--it actually runs the program. In any application, you are always guaranteed that method main will run.
  • 39. C:>javac HelloWorld.java C:> • A successful compile of your java program will return to a bare cursor, as you see here.
  • 40. A Java Application C:>javac HelloWorld.java C:>java HelloWorld Hello World! • To run your compiled Application, you enter lowercase java HelloWorld on the command line. • Notice, the “.class” extension is omitted.
  • 41. Now load the JDK1.4.1, the documentation, change the class path and write your first Java program.
  • 42. Chapter 2 Introduction to Java Applications
  • 43. Java Applications Are A Series of Classes • A Java Application must have the method main. • A Java Application begins executing at main. • Let’s look at details of an Application:
  • 44. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • This is a basic Application. • Notice the comments. These are required in this course. Java is free form, but you’ll be happy if you get in the habit of documenting like this. • Also, whenever you type an opening curly bracket, type the closing one right away. • Your curly brackets must always--in this class--line up as shown.
  • 45. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • The line above in blue is the class definition for Welcome1. • Every class name must be Capitalized. • Notice, every scrap of code is within this class. • Since it is named Welcome1, this Application is saved in a file called Welcome1.java, spelled exactly the same. • The compiler will make a file called Welcome1.class.
  • 46. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • The word Welcome1 is an identifier. • An identifier is a user-defined word, which consists of: letters digits _ (underscore) $ (a dollar sign) • An identifier cannot begin with a digit.
  • 47. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • Notice that we put the word public before the word class. • This means the class can be called by anything. • The alternatives to public are discussed in Chapter 8.
  • 48. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • The method main is also declared public. • This should just be copied until Chapter 6, when we know methods better.
  • 49. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • void means nothing is returned to the operating system when the program finishes. • The ( String args[] ) works with “arguments” that were passed when the program was executed. • Although you cannot omit it ( String args[] ), we don’t discuss this topic just yet, so please copy it.
  • 50. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • The System.out.println puts the message in quotes on the command console. • If we used System.out.print, then the cursor would not do a carriage return / line the after it prints the This is called feed text. Standard output object. • Notice the opening and closing blue curly brackets. The unit of code enclosed in them is called a “block.” • It is also called the “body” of the method.
  • 51. public class Welcome1 { public static void main( String args[] ) { System.out.println( “Welcome to Java!” ); } // end of main() } // end of class Welcome1 • You will find that you very rarely use this Standard output object. • Instead, you will use the GUI objects. • Notice in red the semicolon. ; All executable statements in Java ends in a semicolon.
  • 52. public class Welcome1 { public static void main( String args[] ) { System.out.print( “Welcome ” ); System.out.println( “to Java!” ); } // end of main() } // end of class Welcome1 • This will still produce the same text as the previous version.
  • 53. public class Welcome1 { public static void main( String args[] ) { System.out.print( “WelcomentonJava! ” ); } // end of main() } // end of class Welcome1 • Notice the “ n ”. The slash is an escape character. It tells the System object that whatever follows the slash is special: n new line t tab r carriage return Welcome to Java! backslash ” quote
  • 54. Primitive Data Types • A variable called number1 actually refers to a place in memory where the value of the variable is stored. • Every variable in Java has a: name, type, size, and a value.
  • 55. Primitive Data Types name Variable names must conform to the rules for identifiers: • they must begin with a letter, • after that they can contain digits, dollar signs and underscores. • Java uses Unicode for its characters, so any “letter” that is valid for a word in any world language is therefore valid for a name in Java.
  • 56. Primitive Data Types type • The “type” appears before the identifier name. • The type can be one of the “primitive data types” or it can be any previously defined class. int num1; • You declare a variable and initialize it on the same line. num1 = 2; • This is a declaration. At this point, the name num1 refers to a location {a pointer} in the computer’s RAM where this variable is stored. int num1=2; • Because an int is declared, we know that four bytes are set aside. • Still, nothing is stored in it yet.
  • 57. Primitive Data Types size • When we assign a type [ int, String] to a variable, we are not only declaring a memory location. • We also decide how big of a number or character is able to be stored in that variable.
  • 58. Primitive Data Types value • Finally, the value is what we want the variable to store.
  • 59. Primitive Data Types • Java is a Strongly-typed language. That means, every variable must be declared as a type. In Java, there are 8 primitive types: • 6 of those refer to numbers --4 for integers types, --2 for floating-point types, • 1 is the character type char, used for characters in Unicode encoding, and • 1 is a boolean type for true or false values.
  • 60. Primitive Data Types int • In contrast to C/C++, an int will always--no matter which operating system--take 4 bytes of storage space. • Because those 4 bytes are set in stone, you can be sure that every JVM that runs your program will be able to store the same size numbers. • int is the most commonly used number size. Range: -2,147,483,648 to 2,147,483,647 (over two billion)
  • 61. Primitive Data Types short • In Java, a short is defined as 2 bytes, no matter which operating system is used. • You would only use this for special situations, such as when speed is really crucial. { For VB programmers, a short is what you’ve come to think of as an int . } Range: -32,768 to 32,767
  • 62. Primitive Data Types long • A long is defined as 8 bytes, no matter which operating system is used. Range: -9,223,372,036,854,775,808L to 9,223,372,036,854,775,807L • Hexadecimal numbers have a prefix: 0x 0x1CFE. • Please notice the upper-case L suffix is appended to any long. This is required.
  • 63. Primitive Data Types byte • A byte is defined as 1 byte, no matter which operating system is used. Range: -128 to 127 • Again, like a short, a byte is only used under rare circumstances.
  • 64. Primitive Data Types float • A float is defined as 4 bytes, no matter which operating system is used. Range: approximately 3.40282347E+38F ( 6-7 significant decimal digits ) • Because there are so few decimal places available, float is not used all that often.
  • 65. Primitive Data Types double • A double is defined as 8 bytes, no matter which operating system is used. Range: approximately 1.79769313486231570E+308 ( 15 significant decimal digits ) • “double is the one to have when you’re having more than one--decimal place, that is.” • This is the most common choice for any decimal. • double is the default, not float, therefore, no special character is appended. (See red arrow.)
  • 66. Primitive Data Types char • A char is defined as 2 bytes, no matter which operating system is used. A char type always refers to a character in the Unicode encoding scheme. [uFFFF u is the escape character syntax] About 65,536 different characters can be represented. • Single quotes denote a char constant „H‟ is a char constant “H” is a string that happens to only contain a single character.
  • 67. Primitive Data Types char • A char is defined as 2 bytes. A char type is a single Unicode character. [uFFFF u is the escape character syntax--65,536 different characters can be represented.] • Single quotes denote a single-letter char constant „H‟ is a char constant. “H” is a String that happens to only contain a single character--it is not a char. This is a syntax error! The compiler will complain.
  • 68. Primitive Data Types boolean • A boolean type has only two values. • In contrast to C/C++, in Java 0 and 1 cannot stand in for true or false. • A boolean type must be assigned the value of the constants true or false. [Meaning, these exact lowercase words.]
  • 69. Java Math Operators • Addition + • Subtraction - • Multiplication * • Division / • Modulus % All are binary operators, i.e., they work with two numbers. They are executed according to the rules for operator precedence. [page 1240] (There is no operator for exponentiation in Java)
  • 70. Java Math Operators • Multiplication * • What happens if you multiply variables of different types? int x = 2; double y = 3.889, sum = 0.000; sum = y * x; • The integer will be temporarily converted to a double and two doubles will be multiplied. • Afterwards, the original integer is unchanged.
  • 71. Java Math Operators • Rules for Temporary Conversions 1st Priority: If either of the operands is of type double, then the other one is converted to double for the calculation. 2nd Priority: Otherwise, if either of the operands is of type float, then the other one is converted to float for the calculation. 3rd Priority: Otherwise, if any of the operands is of type long, then the other one is converted to long for the calculation. Note: these conversions are automatic because none of them result in a loss of accuracy.
  • 72. Java Math Operators • Static Casts So, what happens when you desire to convert a double to a float? Information will inevitably be lost. • You accomplish this using a cast. int x = 2, sum = 0; double y = 3.889; sum = (int)y * x; { sum is now equal to 6 } • Here, a value of just 3 will be used for y. • If you want to round y, you a method from class Math: sum = (int)Math.round(y) * x;
  • 73. Java Math Operators • Division / • Division can lead to unexpected results: If both operands are integers, then the result of the division is also an integer. Any fractional part of the division is discarded. Therefore: 17/3 = 5
  • 74. Java Math Operators • Modulus % • The modulus operator is confusing at first, but eventually it becomes your good friend. In contrast to the division operator, it returns the remainder of any division. The modulus operator can only be used when both operands are integers. 17 % 3 = 2 You say this “17 modulus 3 equals 2”
  • 75. Comparison Operators • These are used for selection structures: equality == not equal != greater than > less than < greater than or equal >= less than or equal <=
  • 76. Comparison Operators • The equality operator is a common source of mistakes: equality == Note that two equal signs are always used. The single equal sign [ = ] is only used for assignment, that is, assigning the value on the right to the variable on the left. num1 = 33;
  • 77. Comparison Operators • When you make a compound symbol using the equal sign, the equal sign is always on the right: equality == not equal != greater than or equal >= less than or equal <=