SlideShare a Scribd company logo
OCA EXAM 8
CHAPTER 1 – Java Building Blocks
By İbrahim Kürce
Brief of OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
Jeanne Boyarsky, Scott Selikoff
CHAPTER 1
Info About Exam
 The OCA exam has varied between 60 and 90 questions since it was
introduced. The score to pass has varied between 60 percent and 80
percent. The time allowed to take the exam has varied from two hours to
two-and-a-half hours.
 http://www.selikoff.net/java-oca-8-programmer-i-study-guide/
 Some testing centers are nice and professionally run. Others stick you in a
closet with lots of people talking around you.
Chapter 1 – Java Building Blocks
 In Java programs, classes are the basic building blocks.
 When defining a class, you describe all the parts and characteristics of one
of those building blocks.
 An object is a runtime instance of a class in memory.
 All the various objects of all the different classes represent the state of your
program.
Fields and Methods
 Java classes have two primary elements: methods, often called functions or
procedures in other languages, and fields, more generally known as
variables.
 Together these are called the members of the class.
 Variables hold the state of the program, and methods operate on that
state.
 Java calls a word with special meaning a keyword.
 The public keyword on line 1 means the class can be used by other classes.
 The class keyword indicates you're defining a class.
Fields and Methods
 Animal gives the name of the class.
 This one has a special return type called void.
 void means that no value at all is returned.
 This method requires information be supplied to it from the calling method; this
information is called a parameter.
 The full declaration of a method is called a method signature.
Comments
 Another common part of the code is called a comment. Because
comments aren't executable code, you can place them anywhere.
// comment until end of line
/* Multiple
* line comment
*/
/**
* Javadoc multiple-line comment
* @author Jeanne and Scott
*/
Comments
 This comment is similar to a multiline comment except it starts with /**. This
special syntax tells the Javadoc tool to pay attention to the comment.
Comments
 anteater is in a multiline comment. Everything between /* and */ is part of a
multiline comment— even if it includes a single-line comment within it!
 bear is your basic single-line comment.
 cat and dog are also single-line comments. Everything from // to the end of
the line is part of the comment, even if it is another type of comment.
 elephant is your basic multiline comment.
 The line with ferret is interesting in that it doesn't compile. Everything from
the first /* to the first */ is part of the comment, which means the compiler
sees something like this: /* */ */
 We have a problem. There is an extra */. That's not valid syntax— a fact the
compiler is happy to inform you about.
Classes vs. Files
 You can put two classes in the same file. When you do so, at most one of
the classes in the file is allowed to be public.
 If you do have a public class, it needs to match the filename.
 Code would not compile in a file named Animal2.java. It would be
Animal.java
Writing a main() Method
 A Java program begins execution with its main() method.
 A main() method is the gateway between the startup of a Java process,
which is managed by the Java Virtual Machine (JVM).
 To compile Java code, the file must have the extension .java. The name of
the file must match the name of the class. The result is a file of bytecode by
the same name, but with a .class filename extension.
Writing a main() Method
 Bytecode consists of instructions that the JVM knows how to execute.
Notice that we must omit the .class extension to run Zoo.java because the
period has a reserved meaning in the JVM.
 The keyword public is what's called an access modifier.
 The keyword static binds a method to its class so it can be called by just the
class name, as in, for example, Zoo.main().
 The keyword void represents the return type. A method that returns no data
returns control to the caller silently. In general, it's good practice to use void
for methods that change an object's state.
Writing a main() Method
Understanding Package Declarations
and Imports
 Java puts classes in packages.
 import statements tell Java which packages to look in for classes.
Willcards
 It doesn't import child packages, fields, or methods; it imports only classes.
 You might think that including so many classes slows down your program,
but it doesn't. The compiler figures out what's actually needed.
 There's one special package in the Java world called java.lang.
 You can still type this package in an import statement, but you don't have
to.
Naming Conflicts
 A common example of this is the Date class. Java provides
implementations of java.util.Date and java.sql.Date.
 When the class is found in multiple packages, Java gives you the compiler
error:
 The type Date is ambiguous
 If you explicitly import a class name, it takes precedence over any
wildcards present.
Creating a New Package
 Up to now, all the code we've written in this chapter has been in the default
package.
Creating a New Package
 cd C: temp
 javac packagea/ ClassA.java packageb/ ClassB.java
 java packageb.ClassB
Code Formatting on Exam
 You should expect to see code like the following and to be asked whether
it compiles.
Creating Objects
Constructors
 To create an instance of a class, all you have to do is write new before it.
For example:
 Random r = new Random();
 There are two key points to note about the constructor: the name of the
constructor matches the name of the class, and there's no return type.
 When you see a method name beginning with a capital letter and having
a return type, pay special attention to it. It is not a constructor since there's
a return type.
Reading and Writing Object Fields
Instance Initializer Blocks
 When you learned about methods, you saw braces ({}). The code between
the braces is called a code block.
 Code blocks appear outside a method. These are called instance
initializers.
Order of Initialization
 Fields and instance initializer blocks are run in the order in which they
appear in the file. The constructor runs after all fields and instance initializer
blocks have run.
Order of Initialization
 Order matters for the fields and blocks of code. You can't refer to a
variable before it has been initialized:
{ System.out.println( name); } // DOES NOT COMPILE
private String name = "Fluffy"; //Five.
Distinguishing Between Object References and
Primitives - Primitive Types
 Java has eight built-in data types, referred to as the Java primitive types.
 float and double are used for floating-point (decimal) values.
 A float requires the letter f following the number so Java knows it is a float.
 byte, short, int, and long are used for numbers without decimal points.
 Each numeric type uses twice as many bits as the smaller similar type. For
example, short uses twice as many bits as byte does.
Primitive Types
 You won't be asked about the exact sizes of most of these types.
 You do not have to know this for the exam, but the maximum number an
int can hold is 2,147,483,647.
 How do we know this? One way is to have Java tell us:
System.out.println( Integer.MAX_VALUE);
 When a number is present in the code, it is called a literal.
 By default, Java assumes you are defining an int value with a literal.
long max = 3123456789; // DOES NOT COMPILE
long max = 3123456789L; // now Java knows it is a long
Primitive Types
 octal (digits 0– 7), which uses the number 0 as a prefix— for example, 017
 hexadecimal (digits 0– 9 and letters A– F), which uses the number 0
followed by x or X as a prefix— for example, 0xFF
 binary (digits 0– 1), which uses the number 0 followed by b or B as a prefix—
for example, 0b10
 Feature added in Java 7.
int million1 = 1000000;
int million2 = 1_000_000;
Reference Types
 A reference type refers to an object (an instance of a class).
 Unlike primitive types that hold their values in the memory where the
variable is allocated, references do not hold the value of the object they
refer to. Instead, a reference “points” to an object by storing the memory
address where the object is located, a concept referred to as a pointer.
 Unlike other languages, Java does not allow you to learn what the physical
memory address is.
java.util.Date today;
 The today variable is a reference of type Date and can only point to a
Date object.
Reference Types
 A reference can be assigned to another object of the same type.
 A reference can be assigned to a new object using the new keyword.
Key Differences
 int value = null; // DOES NOT COMPILE
 Primitives do not have methods declared on them.
int len = 1;
int bad = len.length(); // DOES NOT COMPILE
 All the primitive types have lowercase type names. All classes that come
with Java begin with uppercase.
Declaring and Initializing Variables
 A variable is a name for a piece of memory that stores data.
String zooName;
int numberAnimals;
zooName = "The Best Zoo";
numberAnimals = 100;
String zooName = "The Best Zoo";
int numberAnimals = 100;
Declaring Multiple Variables
 String s1, s2;
 String s3 = "yes", s4 = "no";
 int num, String value; // DOES NOT COMPILE
 Multiple variables of different types in the same statement is not allowed.
Identifiers
 It probably comes as no surprise that Java has precise rules about identifier
names.
 There are only three rules to remember for legal identifiers:
The name must begin with a letter or the symbol $ or _.
Subsequent characters may also be numbers.
You cannot use the same name as a Java reserved word.
Identifiers
 const and goto aren't actually used in Java. They are reserved so that people
coming from other languages don't use them by accident— and in theory, in
case Java wants to use them one day.
 Legal examples,
 okidentifier
 $OK2Identifier
 _alsoOK1d3ntifi3r
 __SStillOkbutKnotsonice$
 Not legal ones,
 3DPointClass // identifiers cannot begin with a number
 hollywood@ vine // @ is not a letter, digit, $ or _
 *$coffee // * is not a letter, digit, $ or _
Identifiers
 Java has conventions in writing code that is CamelCase. In CamelCase,
each word begins with an uppercase letter. This makes multiple-word
variable names easier to read. Which would you rather read: Thisismyclass
name or ThisIsMyClass name?
Understanding Default Initialization of
Variables – Local Variables
 A local variable is a variable defined within a method.
 Local variables must be initialized before use.
 The compiler is also smart enough to recognize initializations that are more
complex.
Instance and Class Variables
 Variables that are not local variables are known as instance variables or
class variables.
 Instance variables are also called fields.
 Class variables are shared across multiple objects. You can tell a variable is
a class variable because it has the keyword static before it.
 Instance and class variables do not require you to initialize them. As soon as
you declare these variables, they are given a default value.
Understanding Variable Scope
 There are two local variables in this method. bitesOfCheese is declared
inside the method. piecesOfCheese is called a method parameter. It is also
local to the method.
 Both of these variables are said to have a scope local to the method.
 This means they cannot be used outside the method.
Understanding Variable Scope
 Local variables— in scope from declaration to end of block
 Instance variables— in scope from declaration until object garbage
collected
 Class variables— in scope from declaration until program ends
Ordering Elements in Class
 Think of the acronym PIC (picture): package, import, and class.
 Multiple classes can be defined in the same file, but only one of them is
allowed to be public.
Ordering Elements in Class
 The public class matches the name of the file.
 A file is also allowed to have neither class be public. As long as there isn't
more than one public class in a file, it is okay.
Destroying Objects
 Java provides a garbage collector to automatically look for objects that
aren't needed anymore.
 All Java objects are stored in your program memory's heap.
 The heap, which is also referred to as the free store, represents a large pool
of unused memory allocated to your Java application.
Garbage Collection
 Garbage collection refers to the process of automatically freeing memory on
the heap by deleting objects that are no longer reachable in your program.
 There are many different algorithms for garbage collection, but you don't need
to know any of them for the exam.
 You do need to know that System.gc() is not guaranteed to run, and you should
be able to recognize when objects become eligible for garbage collection.
 It meekly suggests that now might be a good time for Java to kick off a
garbage collection run. Java is free to ignore the request.
 An object is no longer reachable when one of two situations occurs:
 The object no longer has any references pointing to it.
 All references to the object have gone out of scope.
finalize()
 Java allows objects to implement a method called finalize() that might get
called.
 Just keep in mind that it might not get called and that it definitely won't be
called twice.
Benefits of Java
 Java has some key benefits that you'll need to know for the exam:
 Object Oriented
 Encapsulation: Java supports access modifiers to protect data from unintended
access and modification.
 Platform Independent: Java is an interpreted language because it gets compiled
to bytecode. This is known as “write once, run everywhere.” On the OCP exam,
you'll learn that it is possible to write code that does not run everywhere. For
example, you might refer to a file in a specific directory.
 Robust: One of the major advantages of Java over C + + is that it prevents
memory leaks. Java manages memory on its own and does garbage collection
automatically.
 Simple: Java was intended to be simpler than C + +.
 Secure: Java code runs inside the JVM.
Question
Answer
 A,C,D,E
Question
Answer
 A,E
Question
Answer
 A=0

More Related Content

What's hot

Java String
Java StringJava String
Java String
Java2Blog
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
İbrahim Kürce
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
ParvizMirzayev2
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
String in java
String in javaString in java
6. static keyword
6. static keyword6. static keyword
6. static keyword
Indu Sharma Bhardwaj
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaSanjeev Tripathi
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
Jeevesh Pandey
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
Java codes
Java codesJava codes
Java codes
Hussain Sherwani
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
OCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class DesignOCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class Design
İbrahim Kürce
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 

What's hot (20)

Java String
Java StringJava String
Java String
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
 
this keyword in Java.pptx
this keyword in Java.pptxthis keyword in Java.pptx
this keyword in Java.pptx
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
String in java
String in javaString in java
String in java
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Java basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini indiaJava basic tutorial by sanjeevini india
Java basic tutorial by sanjeevini india
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Java codes
Java codesJava codes
Java codes
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
OCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class DesignOCA Java SE 8 Exam Chapter 5 Class Design
OCA Java SE 8 Exam Chapter 5 Class Design
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java input
Java inputJava input
Java input
 

Similar to OCA Java SE 8 Exam Chapter 1 Java Building Blocks

Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
Professional Guru
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
Math-Circle
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
Darshan Gohel
 
Java PPt.ppt
Java PPt.pptJava PPt.ppt
Java PPt.ppt
NavneetSheoran3
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2Raghu nath
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
SHIBDASDUTTA
 
INTRODUCTION TO JAVA
INTRODUCTION TO JAVAINTRODUCTION TO JAVA
INTRODUCTION TO JAVA
Pintu Dasaundhi (Rahul)
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
VasanthiMuniasamy2
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
javaopps concepts
javaopps conceptsjavaopps concepts
javaopps concepts
Nikhil Agrawal
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
University of Potsdam
 
DAY_1.1.pptx
DAY_1.1.pptxDAY_1.1.pptx
DAY_1.1.pptx
ishasharma835109
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1ppJ. C.
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
Hamid Ghorbani
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
University of Potsdam
 

Similar to OCA Java SE 8 Exam Chapter 1 Java Building Blocks (20)

Introduction to JAVA
Introduction to JAVAIntroduction to JAVA
Introduction to JAVA
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
 
Basics java programing
Basics java programingBasics java programing
Basics java programing
 
java01.ppt
java01.pptjava01.ppt
java01.ppt
 
Java PPt.ppt
Java PPt.pptJava PPt.ppt
Java PPt.ppt
 
java
java java
java
 
Basics of java 2
Basics of java 2Basics of java 2
Basics of java 2
 
Core_java_ppt.ppt
Core_java_ppt.pptCore_java_ppt.ppt
Core_java_ppt.ppt
 
INTRODUCTION TO JAVA
INTRODUCTION TO JAVAINTRODUCTION TO JAVA
INTRODUCTION TO JAVA
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Computer Programming 2
Computer Programming 2 Computer Programming 2
Computer Programming 2
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
javaopps concepts
javaopps conceptsjavaopps concepts
javaopps concepts
 
Java Object Oriented Programming
Java Object Oriented Programming Java Object Oriented Programming
Java Object Oriented Programming
 
DAY_1.1.pptx
DAY_1.1.pptxDAY_1.1.pptx
DAY_1.1.pptx
 
Chapter1pp
Chapter1ppChapter1pp
Chapter1pp
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
 

More from İbrahim Kürce

Java By Comparison
Java By ComparisonJava By Comparison
Java By Comparison
İbrahim Kürce
 
Bir Alim - Fuat Sezgin
Bir Alim - Fuat SezginBir Alim - Fuat Sezgin
Bir Alim - Fuat Sezgin
İbrahim Kürce
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
İbrahim Kürce
 
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
İbrahim Kürce
 
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
İbrahim Kürce
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
İbrahim Kürce
 
Effective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying ObjectsEffective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying Objects
İbrahim Kürce
 

More from İbrahim Kürce (8)

Java By Comparison
Java By ComparisonJava By Comparison
Java By Comparison
 
Bir Alim - Fuat Sezgin
Bir Alim - Fuat SezginBir Alim - Fuat Sezgin
Bir Alim - Fuat Sezgin
 
The Go Programing Language 1
The Go Programing Language 1The Go Programing Language 1
The Go Programing Language 1
 
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
Effective Java - Madde 2: Birçok parametreli yapılandırıcıyla karşılaşırsan k...
 
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
Effective Java - Madde 1: Yapılandırıcılar yerine statik fabrika(factory) met...
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Effective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All ObjectsEffective Java - Chapter 3: Methods Common to All Objects
Effective Java - Chapter 3: Methods Common to All Objects
 
Effective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying ObjectsEffective Java - Chapter 2: Creating and Destroying Objects
Effective Java - Chapter 2: Creating and Destroying Objects
 

Recently uploaded

Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Yara Milbes
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
Roshan Dwivedi
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
Boni García
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 

Recently uploaded (20)

Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Vitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdfVitthal Shirke Java Microservices Resume.pdf
Vitthal Shirke Java Microservices Resume.pdf
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaTop 7 Unique WhatsApp API Benefits | Saudi Arabia
Top 7 Unique WhatsApp API Benefits | Saudi Arabia
 
Launch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in MinutesLaunch Your Streaming Platforms in Minutes
Launch Your Streaming Platforms in Minutes
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket ManagementUtilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
Utilocate provides Smarter, Better, Faster, Safer Locate Ticket Management
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)APIs for Browser Automation (MoT Meetup 2024)
APIs for Browser Automation (MoT Meetup 2024)
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 

OCA Java SE 8 Exam Chapter 1 Java Building Blocks

  • 1. OCA EXAM 8 CHAPTER 1 – Java Building Blocks By İbrahim Kürce Brief of OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808 Jeanne Boyarsky, Scott Selikoff
  • 2. CHAPTER 1 Info About Exam  The OCA exam has varied between 60 and 90 questions since it was introduced. The score to pass has varied between 60 percent and 80 percent. The time allowed to take the exam has varied from two hours to two-and-a-half hours.  http://www.selikoff.net/java-oca-8-programmer-i-study-guide/  Some testing centers are nice and professionally run. Others stick you in a closet with lots of people talking around you.
  • 3. Chapter 1 – Java Building Blocks  In Java programs, classes are the basic building blocks.  When defining a class, you describe all the parts and characteristics of one of those building blocks.  An object is a runtime instance of a class in memory.  All the various objects of all the different classes represent the state of your program.
  • 4. Fields and Methods  Java classes have two primary elements: methods, often called functions or procedures in other languages, and fields, more generally known as variables.  Together these are called the members of the class.  Variables hold the state of the program, and methods operate on that state.  Java calls a word with special meaning a keyword.  The public keyword on line 1 means the class can be used by other classes.  The class keyword indicates you're defining a class.
  • 5. Fields and Methods  Animal gives the name of the class.  This one has a special return type called void.  void means that no value at all is returned.  This method requires information be supplied to it from the calling method; this information is called a parameter.  The full declaration of a method is called a method signature.
  • 6. Comments  Another common part of the code is called a comment. Because comments aren't executable code, you can place them anywhere. // comment until end of line /* Multiple * line comment */ /** * Javadoc multiple-line comment * @author Jeanne and Scott */
  • 7. Comments  This comment is similar to a multiline comment except it starts with /**. This special syntax tells the Javadoc tool to pay attention to the comment.
  • 8. Comments  anteater is in a multiline comment. Everything between /* and */ is part of a multiline comment— even if it includes a single-line comment within it!  bear is your basic single-line comment.  cat and dog are also single-line comments. Everything from // to the end of the line is part of the comment, even if it is another type of comment.  elephant is your basic multiline comment.  The line with ferret is interesting in that it doesn't compile. Everything from the first /* to the first */ is part of the comment, which means the compiler sees something like this: /* */ */  We have a problem. There is an extra */. That's not valid syntax— a fact the compiler is happy to inform you about.
  • 9. Classes vs. Files  You can put two classes in the same file. When you do so, at most one of the classes in the file is allowed to be public.  If you do have a public class, it needs to match the filename.  Code would not compile in a file named Animal2.java. It would be Animal.java
  • 10. Writing a main() Method  A Java program begins execution with its main() method.  A main() method is the gateway between the startup of a Java process, which is managed by the Java Virtual Machine (JVM).  To compile Java code, the file must have the extension .java. The name of the file must match the name of the class. The result is a file of bytecode by the same name, but with a .class filename extension.
  • 11. Writing a main() Method  Bytecode consists of instructions that the JVM knows how to execute. Notice that we must omit the .class extension to run Zoo.java because the period has a reserved meaning in the JVM.  The keyword public is what's called an access modifier.  The keyword static binds a method to its class so it can be called by just the class name, as in, for example, Zoo.main().  The keyword void represents the return type. A method that returns no data returns control to the caller silently. In general, it's good practice to use void for methods that change an object's state.
  • 13. Understanding Package Declarations and Imports  Java puts classes in packages.  import statements tell Java which packages to look in for classes.
  • 14. Willcards  It doesn't import child packages, fields, or methods; it imports only classes.  You might think that including so many classes slows down your program, but it doesn't. The compiler figures out what's actually needed.  There's one special package in the Java world called java.lang.  You can still type this package in an import statement, but you don't have to.
  • 15. Naming Conflicts  A common example of this is the Date class. Java provides implementations of java.util.Date and java.sql.Date.  When the class is found in multiple packages, Java gives you the compiler error:  The type Date is ambiguous  If you explicitly import a class name, it takes precedence over any wildcards present.
  • 16. Creating a New Package  Up to now, all the code we've written in this chapter has been in the default package.
  • 17. Creating a New Package  cd C: temp  javac packagea/ ClassA.java packageb/ ClassB.java  java packageb.ClassB
  • 18. Code Formatting on Exam  You should expect to see code like the following and to be asked whether it compiles.
  • 19. Creating Objects Constructors  To create an instance of a class, all you have to do is write new before it. For example:  Random r = new Random();  There are two key points to note about the constructor: the name of the constructor matches the name of the class, and there's no return type.  When you see a method name beginning with a capital letter and having a return type, pay special attention to it. It is not a constructor since there's a return type.
  • 20. Reading and Writing Object Fields
  • 21. Instance Initializer Blocks  When you learned about methods, you saw braces ({}). The code between the braces is called a code block.  Code blocks appear outside a method. These are called instance initializers.
  • 22. Order of Initialization  Fields and instance initializer blocks are run in the order in which they appear in the file. The constructor runs after all fields and instance initializer blocks have run.
  • 23. Order of Initialization  Order matters for the fields and blocks of code. You can't refer to a variable before it has been initialized: { System.out.println( name); } // DOES NOT COMPILE private String name = "Fluffy"; //Five.
  • 24. Distinguishing Between Object References and Primitives - Primitive Types  Java has eight built-in data types, referred to as the Java primitive types.  float and double are used for floating-point (decimal) values.  A float requires the letter f following the number so Java knows it is a float.  byte, short, int, and long are used for numbers without decimal points.  Each numeric type uses twice as many bits as the smaller similar type. For example, short uses twice as many bits as byte does.
  • 25. Primitive Types  You won't be asked about the exact sizes of most of these types.  You do not have to know this for the exam, but the maximum number an int can hold is 2,147,483,647.  How do we know this? One way is to have Java tell us: System.out.println( Integer.MAX_VALUE);  When a number is present in the code, it is called a literal.  By default, Java assumes you are defining an int value with a literal. long max = 3123456789; // DOES NOT COMPILE long max = 3123456789L; // now Java knows it is a long
  • 26. Primitive Types  octal (digits 0– 7), which uses the number 0 as a prefix— for example, 017  hexadecimal (digits 0– 9 and letters A– F), which uses the number 0 followed by x or X as a prefix— for example, 0xFF  binary (digits 0– 1), which uses the number 0 followed by b or B as a prefix— for example, 0b10  Feature added in Java 7. int million1 = 1000000; int million2 = 1_000_000;
  • 27. Reference Types  A reference type refers to an object (an instance of a class).  Unlike primitive types that hold their values in the memory where the variable is allocated, references do not hold the value of the object they refer to. Instead, a reference “points” to an object by storing the memory address where the object is located, a concept referred to as a pointer.  Unlike other languages, Java does not allow you to learn what the physical memory address is. java.util.Date today;  The today variable is a reference of type Date and can only point to a Date object.
  • 28. Reference Types  A reference can be assigned to another object of the same type.  A reference can be assigned to a new object using the new keyword.
  • 29. Key Differences  int value = null; // DOES NOT COMPILE  Primitives do not have methods declared on them. int len = 1; int bad = len.length(); // DOES NOT COMPILE  All the primitive types have lowercase type names. All classes that come with Java begin with uppercase.
  • 30. Declaring and Initializing Variables  A variable is a name for a piece of memory that stores data. String zooName; int numberAnimals; zooName = "The Best Zoo"; numberAnimals = 100; String zooName = "The Best Zoo"; int numberAnimals = 100;
  • 31. Declaring Multiple Variables  String s1, s2;  String s3 = "yes", s4 = "no";  int num, String value; // DOES NOT COMPILE  Multiple variables of different types in the same statement is not allowed.
  • 32. Identifiers  It probably comes as no surprise that Java has precise rules about identifier names.  There are only three rules to remember for legal identifiers: The name must begin with a letter or the symbol $ or _. Subsequent characters may also be numbers. You cannot use the same name as a Java reserved word.
  • 33. Identifiers  const and goto aren't actually used in Java. They are reserved so that people coming from other languages don't use them by accident— and in theory, in case Java wants to use them one day.  Legal examples,  okidentifier  $OK2Identifier  _alsoOK1d3ntifi3r  __SStillOkbutKnotsonice$  Not legal ones,  3DPointClass // identifiers cannot begin with a number  hollywood@ vine // @ is not a letter, digit, $ or _  *$coffee // * is not a letter, digit, $ or _
  • 34. Identifiers  Java has conventions in writing code that is CamelCase. In CamelCase, each word begins with an uppercase letter. This makes multiple-word variable names easier to read. Which would you rather read: Thisismyclass name or ThisIsMyClass name?
  • 35. Understanding Default Initialization of Variables – Local Variables  A local variable is a variable defined within a method.  Local variables must be initialized before use.  The compiler is also smart enough to recognize initializations that are more complex.
  • 36. Instance and Class Variables  Variables that are not local variables are known as instance variables or class variables.  Instance variables are also called fields.  Class variables are shared across multiple objects. You can tell a variable is a class variable because it has the keyword static before it.  Instance and class variables do not require you to initialize them. As soon as you declare these variables, they are given a default value.
  • 37. Understanding Variable Scope  There are two local variables in this method. bitesOfCheese is declared inside the method. piecesOfCheese is called a method parameter. It is also local to the method.  Both of these variables are said to have a scope local to the method.  This means they cannot be used outside the method.
  • 38. Understanding Variable Scope  Local variables— in scope from declaration to end of block  Instance variables— in scope from declaration until object garbage collected  Class variables— in scope from declaration until program ends
  • 39. Ordering Elements in Class  Think of the acronym PIC (picture): package, import, and class.  Multiple classes can be defined in the same file, but only one of them is allowed to be public.
  • 40. Ordering Elements in Class  The public class matches the name of the file.  A file is also allowed to have neither class be public. As long as there isn't more than one public class in a file, it is okay.
  • 41. Destroying Objects  Java provides a garbage collector to automatically look for objects that aren't needed anymore.  All Java objects are stored in your program memory's heap.  The heap, which is also referred to as the free store, represents a large pool of unused memory allocated to your Java application.
  • 42. Garbage Collection  Garbage collection refers to the process of automatically freeing memory on the heap by deleting objects that are no longer reachable in your program.  There are many different algorithms for garbage collection, but you don't need to know any of them for the exam.  You do need to know that System.gc() is not guaranteed to run, and you should be able to recognize when objects become eligible for garbage collection.  It meekly suggests that now might be a good time for Java to kick off a garbage collection run. Java is free to ignore the request.  An object is no longer reachable when one of two situations occurs:  The object no longer has any references pointing to it.  All references to the object have gone out of scope.
  • 43. finalize()  Java allows objects to implement a method called finalize() that might get called.  Just keep in mind that it might not get called and that it definitely won't be called twice.
  • 44. Benefits of Java  Java has some key benefits that you'll need to know for the exam:  Object Oriented  Encapsulation: Java supports access modifiers to protect data from unintended access and modification.  Platform Independent: Java is an interpreted language because it gets compiled to bytecode. This is known as “write once, run everywhere.” On the OCP exam, you'll learn that it is possible to write code that does not run everywhere. For example, you might refer to a file in a specific directory.  Robust: One of the major advantages of Java over C + + is that it prevents memory leaks. Java manages memory on its own and does garbage collection automatically.  Simple: Java was intended to be simpler than C + +.  Secure: Java code runs inside the JVM.