basic core java up to operator

6,508 views
6,314 views

Published on

This is a simple ppt it provides introduction of core java difference of c++ and java and operators used in core java

Published in: Education, Technology
1 Comment
11 Likes
Statistics
Notes
  • Thanks. We've incorporated some of these learnings into preparing the Top 10 Java Interview Questions

    http://www.slideshare.net/iimjobs/top-10-java-interview-questions-and-answers
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
6,508
On SlideShare
0
From Embeds
0
Number of Embeds
3,068
Actions
Shares
0
Downloads
1
Comments
1
Likes
11
Embeds 0
No embeds

No notes for slide

basic core java up to operator

  1. 1. Chapter 1Introduction
  2. 2. Java’sMajor Advantage over C & C++
  3. 3. Because pointers were a major source ofbugs in C and C++, Gosling omittedpointers entirely from Java.• Actually, pointers are still an importantpart of the language--all objects arereferenced by pointers--but the languagehandles them, not the programmer.
  4. 4. Java’s Origins in C & C++Thus, it has been said that... “Java is C without the Guns and Knives.”
  5. 5. Java Architecture• By now, Java itself has matured into its3rd version, named Java 2. This course isbased on Java 2. The most current is Java2 (1.5.1)• Java is Object-Oriented--that meanseverything in the language behaves likean object.• What exactly that means will beexplained in the coming weeks.
  6. 6. Java ArchitectureJava’s Architecture comes from four separatebut intertwined technologies:• the Java Programming Language• the Java class file format• the Java API, or Application Programming Interface• the Java Virtual Machine
  7. 7. Java ArchitectureSource programs are written in the Java ProgrammingLanguage.All procedural code falls within methods.Programs are compiled into Java class files.Classes run in the Java Virtual Machine.
  8. 8. Java Architecture• When a Java program runs, it is assisted byother classes in the Java the ApplicationProgramming Interface, or API.
  9. 9. 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
  10. 10. Java Architecture• The Java Platform is unique, because itcan work without modification on any platform, on any operating system, if that platform has a “Java Virtual Machine.”
  11. 11. Java Architecture Java What is the Virtual ? MachineComparison of a typical ProceduralProgram with a Java Program:• In a typical C program, the source code iscompiled into a native machine languagemodule that consists of 1’s and 0’s.
  12. 12. C Source Code C object module compiled into machine language• The machine language is specifically tailoredto one OS, be it Wintel, Mac, UNIX or MVS. •Therefore, it is impossible for one objectmodule to be portable between platforms.
  13. 13. Java Architecture Java “bytecode”In contrast to conventional programminglanguages, a Java program is not compiledinto native machine language.• Instead, Java makes bytecode.• Bytecode is the result of a “compile”, butthe compile results in an intermediate formthat stops short of native machine-specificcode.
  14. 14. Java Architecture• Instead of making a machine languagenative code for each particular OS, Javamakes a single, universal bytecode modulethat feeds into any Java Virtual Machine(JVM).• Each OS has its own differentimplementation of the Java Virtual Machine.
  15. 15. Java Architecture• The JVM sets up its own world withinyour RAM.• The JVM creates an internalsoftware-only sub-computer within the OS.• The bytecode talks to the JVM, and theJVM talks to the Operating System.
  16. 16. Java Architecture• Thus, you get the Holy Grail of software reuse: “Write Once, Run Anywhere”.
  17. 17. Java SourceThe You can easily see why Billbytecode Gates isn’t in love with Java!is methalf-wayby theJVM. JVM-Win JVM-Mac JVM-Unix JVM-IBM
  18. 18. 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.
  19. 19. Security and the “Sandbox
  20. 20. C and C++ are famous for speed. • One reason they are fast is because Cand C++ don’t do things like checking thebounds of arrays. • In C orC++, a program can walk off the edge of anarray and invade the memory space beyond. • Hackers love that about C and C++.
  21. 21. Security and the “Sandbox”• Another weakness of C/C++, that is afavorite among Hackers, is the BufferOverflow.• In this attack, the Hacker floods too muchdata into a buffer and whatever overflows itis turned loose on the system.• Java solves these problems
  22. 22. 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.”
  23. 23. 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
  24. 24. 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.
  25. 25. Security and the “Sandbox”• You see, preventing problems is a majordesign consideration in Java.• This idea led to the most import aspect ofJava: Object Orientation.• Object Orientation protects data and lets aprogram do only what is explicitly permitted.• You could say Java is pessimistic.
  26. 26. Objects in Java• In Java, Object Orientation is sopervasive that it’s nearly impossibleto write a strictly procedural programin the language.
  27. 27. 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 extensionXxx.java
  28. 28. Objects in Java• If I write a Java program called: Hello.java then, when compiled, this program willbe called: Hello.class
  29. 29. Objects in Java• A class object is compiled Java code thatcontains its own data variables, calledmembers, and sections of procedural codecalled methods. If you have programmed in COBOL, amethod is like a paragraph you perform. If you have programmed in C or C++, amethod is like a function your program calls.
  30. 30. Objects in Java• The combination of the data variables and the methods that are used to read, write or modify those variablesis called a class.
  31. 31. Objects in Java• Java has a rich collection of Class Libraries.• These are also known as the Java API orApplication Programming Interface.• To program in Java, you must i.) Learn the Language, and ii.) Learn the Class Libraries.
  32. 32. Objects in Java• These class libraries greatly simplify yourjob as a Java programmer.• They help you to write complexprograms quickly.• To master Java, you must master theseclass libraries.
  33. 33. Compiling A Java Program• You have created a Java program called Hello.java• To compile it, you run the JDK suppliedutility called: javacC:javac Hello.java If this was successful, a file called: Hello.class will be produced.
  34. 34. First Java Program• The two largest varieties of Javaprograms: Applications Applets
  35. 35. First Java Program• A Java Application is a free-standingprogram that is capable of runningdirectly in the Java Virtual Machine.• A Java Applet is a mini-program that ismuch more limited in its abilities. AnApplet can only run within the context ofan HTML browser.
  36. 36. First Java Program• A Java Application is a free-standingprogram that is capable of runningdirectly in the Java Virtual Machine.• A Java Applet is a mini-program that ismuch more limited in its abilities. AnApplet can only run within the context ofan HTML browser.
  37. 37. A Java Application// HelloWorld.java Our first Java Applicationpublic 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 runsthe program. In any application, you are always guaranteed that methodmain will run.
  38. 38. C:>javac HelloWorld.java C:>• A successful compile of your javaprogram will return to a bare cursor, asyou see here.
  39. 39. A Java Application C:>javac HelloWorld.java C:>java HelloWorld Hello World! • To run your compiled Application,you enter lowercase java HelloWorldon the command line. • Notice, the“.class” extension is omitted.
  40. 40. Now load the JDK1.4.1,the documentation,change the class path andwrite your first Java program.
  41. 41. Chapter 2Introduction to Java Applications
  42. 42. Java Applications Are A Series of Classes• A Java Application must have the methodmain.• A Java Application begins executing atmain.• Let’s look at details of an Application:
  43. 43. 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 habitof documenting like this.• Also, whenever you type an opening curly bracket, typethe closing one right away.• Your curly brackets must always--in this class--line up asshown.
  44. 44. 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 filecalled Welcome1.java, spelled exactly the same.• The compiler will make a file called Welcome1.class.
  45. 45. 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.
  46. 46. 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 wordclass.• This means the class can be called by anything.• The alternatives to public are discussed in Chapter 8.
  47. 47. 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 weknow methods better.
  48. 48. 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 operatingsystem 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.
  49. 49. 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 inquotes on the command console.• If we used System.out.print, then the cursorwould not do a carriage return / line the after it prints the This is called feedtext. Standard output object.• Notice the opening and closing blue curly brackets. Theunit of code enclosed in them is called a “block.”• It is also called the “body” of the method.
  50. 50. 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.
  51. 51. 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 theprevious version.
  52. 52. 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 escapecharacter. It tells the System object that whateverfollows the slash is special:n new line t tab r carriage return Welcome to Java! backslash ” quote
  53. 53. Primitive Data Types• A variable called number1 actually refers to a place inmemory where the value of the variable is stored.• Every variable in Java has a: name, type, size, and a value.
  54. 54. Primitive Data Types nameVariable 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.
  55. 55. Primitive Data Types type• The “type” appears before the identifier name.• The type can be one of the “primitive data types” or itcan 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.
  56. 56. Primitive Data Types size • When we assign a type [ int, String] to avariable, we are not only declaring a memorylocation. • We also decide how big of a number or character is able to be stored in that variable.
  57. 57. Primitive Data Types value • Finally, the value is what we want the variable to store.
  58. 58. Primitive Data Types• Java is a Strongly-typed language. Thatmeans, 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 charactersin Unicode encoding, and• 1 is a boolean type for true or false values.
  59. 59. 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)
  60. 60. 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
  61. 61. Primitive Data Types long • A long is defined as 8 bytes, no matterwhich 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.
  62. 62. 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 underrare circumstances.
  63. 63. 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.
  64. 64. 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.)
  65. 65. Primitive Data Types char • A char is defined as 2 bytes, no matter which operatingsystem is used. A char type always refers to a character in the Unicode encoding scheme. [uFFFF u is the escape character syntax] About65,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.
  66. 66. Primitive Data Types char • A char is defined as 2 bytes. A char type is a singleUnicode character. [uFFFF u is theescape character syntax--65,536 different characters can berepresented.] • 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. Thisis a syntax error! The compiler will complain.
  67. 67. 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.]
  68. 68. Java Math Operators• Addition +• Subtraction -• Multiplication *• Division /• Modulus %All are binary operators, i.e., they work with twonumbers. They are executed according to the rulesfor operator precedence. [page 1240] (There is no operator for exponentiation in Java)
  69. 69. 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 adouble and two doubles will be multiplied.• Afterwards, the original integer is unchanged.
  70. 70. Java Math Operators• Rules for Temporary Conversions1st Priority: If either of the operands is of type double, then the other one is converted todouble for the calculation.2nd Priority: Otherwise, if either of the operands is of type float, then the other one isconverted to float for the calculation.3rd Priority: Otherwise, if any of the operands is of type long, then the other one isconverted to long for the calculation.Note: these conversions are automatic because none of them result in a loss of accuracy.
  71. 71. Java Math Operators• Static CastsSo, what happens when you desire to convert a double toa 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;
  72. 72. Java Math Operators• Division /• Division can lead to unexpected results:If both operands are integers, then the result of thedivision is also an integer.Any fractional part of the division is discarded.Therefore: 17/3 = 5
  73. 73. Java Math Operators• Modulus %• The modulus operator is confusing at first, buteventually it becomes your good friend.In contrast to the division operator, it returns theremainder of any division. The modulus operator canonly be used when both operands are integers. 17 % 3 = 2You say this “17 modulus 3 equals 2”
  74. 74. Comparison Operators• These are used for selectionstructures:equality ==not equal !=greater than >less than <greater than or equal >=less than or equal <=
  75. 75. 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 forassignment, that is, assigning the value on the right to thevariable on the left. num1 = 33;
  76. 76. Comparison Operators• When you make a compound symbol using the equalsign, the equal sign is always on the right:equality ==not equal !=greater than or equal >=less than or equal <=

×