JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

How to prepare for AWS Certified SysOps Administrator Associate Certification exam?

June 13, 2017 by krishna Leave a Comment

In this article, we will explore how to prepare for the AWS Certified SysOps Administrator Associate certification exam. This is the toughest exam in the associate level exam. If you are preparing for the AWS certification, I would suggest you start with the Developer Associate Exam which is the easiest exam. Then you can prepare for the Solutions Architect Associate exam. But, if you are directly writing the SysOps exam, you will learn most of the things that are not covered in other associate level AWS exams.

Image result for sysops administrator

Let’s focus on how to prepare for the AWS sysops administrator certification exam. This article would explain you step-by-step on what are the required resources for preparing this exam. There is no official study guide for this exam. Just reading the AWS website and documents would be enough for the exam.

Official Website

Of course, this is the first place to start your certification journey. You have to visit the official link for the certification details. You will get all the details like a blueprint, sample questions, exam information, video tutorials, etc.

Exam BluePrint

The exam blueprint is the official syllabus for the exam. This blueprint explains what are the concepts that are covered in the exam and break up of the sections and marks that are expected from each section. This should be the first document one should read for preparing for the exam.

Whitepapers

These are the important details that are documented for each service and features that are uploaded by AWS team. This whitepaper contains very useful information about the services. The following are the important whitepapers that are a must-read for the exam:

  • Overview of Security Processes
  • Storage Options in the Cloud
  • Defining Fault-Tolerant Applications in the AWS Cloud
  • Overview of Amazon Web Services
  • Compliance Whitepaper
  • Architecting for the AWS Cloud

Please read these documents multiple times to get a good understanding of the concepts. That is essential for answering the questions in the exam. Note that SysOps exam would expect you to answer the more scenario based questions and deployment related questions.

Practice Questions

Once you have gone through the required study materials, FAQs, and white papers, then it is the time to take the practice questions. AWS provides few samples questions in the website. But, that is not sufficient for the exam. You have to purchase a good quality practice questions in the market to pass the exam. Whizlabs is one of the most popular practice questions for the AWS certification exam. You can buy their 420 questions and practice well.

  • 10 Free Questions
  • 420 Practice Questions

Hands-on practice

Hands-on experience is definitely the best and efficient way to learn AWS concepts. Nothing can give you more confidence in picking the right answer like having done it yourself. This is one of the most

Unfortunately, this also highlights one of the drawbacks of this kind of certification – sometimes the exams lag behind the real world. There are some things that the AWS services now do things that aren’t reflected in the certification exam.

If you don’t have the benefit of using AWS at work, create a new AWS account (i.e. using a new email address) and make the most of the free usage tier. Just set up a billing alarm to send you an email when you are in danger of being charged too much, and you can’t go to wrong.

Person taking an online exam
Photo credit to US News & World Report

Getting to Know the Exam

The exam will have 55 multiple choice questions with an 80-minute time limit. Most questions would be single-answer responses, but some are multiple-answer responses. The exact pass mark does change without notice, according to statistical analysis (see the FAQ). Als,o you have to sign an NDA agreement before taking the exam. You are not allowed to write or talk about the exam details. It is against the policy. So, the practice questions offered by various training are based on the syllabus topics that is shared by Amazon.

Additional Resources

Here is some useful information that would be helpful for you to prepare for this certification exam:

  • Official Link
  • How to prepare for AWS SysOps Administrator Associate exam?
  • What is the salary for an AWS certified developer?
  • Best resources for learning AWS certifications

I hope this article is very informative to understand the basic details that are required to prepare for the AWS Certified SysOps Administrator Associate certification exam. If you have any questions, please write it in the comments section.

Filed Under: Certifications Tagged With: AWS Certification, AWS certified developer, AWS SysOps Administrator Associate

Ultimate Guide for Cracking AWS Certified Solutions Architect Associate Exam

May 28, 2017 by krishna Leave a Comment

In this article, I am going to explain to you how to crack the AWS Certified Solutions Architect Associate Certification Exam with step-by-step preparation. When you complete reading this article, you will have a good idea of where to start and prepare for the solutions architect associate exam. If you have any questions on AWS certification exam, you can write your comments.

Why I have to plan for AWS certification?

Here is the snapshot of advantages for passing the AWS certifications.

Look at the below link for some insights on job opportunities:

  • 15 Top-Paying Certifications for 2016
  • 15 Top Paying IT Certifications In 2016: AWS Certified Solutions Architect Leads At $125K

Some of the other reasons are:

  • Cloud computing is the hot trend and most of the companies are implementing the cloud technologies for their solutions.
  • Amazon Web Services (AWS) is the market leader for cloud computing platform.
  • From the above sources, it is evidence that AWS skills fetch high paying jobs.

Sign-Up for the Amazon Free Tier

AWS free tier is a program by Amazon web service team to use the services. With this program, they offer AWS web services for 12 months with no charges. The free tier is for users who want to test out cloud services for free. In this free tier, you will get almost everything available for the paid version, but with the limited usage.

Those who are studying AWS certification, it is very important to start registration for the free tier and play with the services. It is not possible to pass the exam without any practical knowledge.

Here is the link to sign-up for this free service:
https://aws.amazon.com/

AWS Free Tier for Cloud Services

Exam Overview

Here is the summary of exam details for Solutions Architect Associate certification exam.

● Number of Questions: 60 Multiple Choice Questions (Amazon keeps changing the number of questions)
● Duration: 80 Minutes
● Passing Score: 65% (Amazon keeps changing the passing score)

AWS Certification Resources

Amazon itself hosting a lot of official resources that are very useful to prepare for the Solutions Architect Associate exam. Here is the list of documentation that is very helpful:

  • Sample exam – I would recommend taking sample exam questions to get a general overview of what kind of exam this is.
  • Official preparation site – Go through the Prepare for AWS Certification site. This site has a lot of very useful information that is good for preparing for the AWS certification exams.
  • Hands-on practice – Doing hands-on practice is very important. I have earlier written about sign-up for the free tier. You can use the free tier account for trying few examples for every service. The questions in the exams are scenario-based, which means that hands-on experience is the most important for passing the exam.
  • Whitepapers – The important whitepaper to read is Overview of Security Processes.  After that most important white paper is Storage Options in the AWS Cloud, as it provides patterns and anti-patterns for every storage service on AWS.
  • FAQ – This is one is very important. This would help you to understand each service. There is an FAQ section for each service. You have to go through each of them before attending the exam (Amazon FAQs).

Recommended Books

The AWS Certified Solutions Architect Official Study Guide is your one-stop resource for coverage of the Associate Level Exam. This book can be used as one of the preparation material for this exam. There are some reviews pointed out that some of the sections in this book are outdated.

  • BUY: AWS Certified Solutions Architect Official Study Guide: Associate Exam

Practice Questions

You have to look at the practice questions only when you are done with reading books, white papers, and all other learning things. Practice questions are the final step for testing your knowledge on an understanding of the concepts. Taking multiple questions would help you to easily pass the exam. There are few simulators that offer you the online practice question. Here I am recommending you some of the AWS certification exam simulators:

  • Whizlabs offers 10 Free Questions for Solutions Architect Certification Exam
  • Whizlabs offers 300 Practice Questions for Solutions Architect Certification Exam

Summary

I hope this article would have helped you to understand how to prepare for and pass the AWS Certified Solutions Architect Associate certification exam. If you have any questions, please write it in the comments section.

Filed Under: Certifications Tagged With: Amazon Free Tier, AWS Certification, AWS Certification Resources, AWS Certified Solutions Architect Associate Certification Exam

OCAJP – Wrapper Classes in Java

December 12, 2016 by krishna Leave a Comment

This post is about the OCAJP exam objective “Develop code that uses wrapper classes such as Boolean, Double, and Integer“. In the exam, you will be mainly tested on Autoboxing and Unboxing concepts of Wrapper classes, Using wrapper classes with their corresponding primitive types.

wrapper

This article tests your knowledge on how to use the wrapper class that is mostly asked for the OCAJP certification exams. It is important for you to understand the concepts and practice with a lot of practice questions to master every concept.

What is Wrapper Classes?

Also Read:

  • OCAJP – Switch Statement Practice Questions
  • OCAJP 8 Articles
  • Certification Articles

Wrapper classes that used for wrapping the primitive types. The examples are Integer, Float, etc. These classes are introduced from Java 5 to simplify the use of primitive types as objects. Here are some of the points that are important to remember for the OCAJP certification exams:

  • Generally, when we work with numbers we use primitive data types such as byte, int, long, double, etc.
  • There are certain situations to use objects in place of primitives and the Java platform provides wrapper classes for each of the primitive data types.
  • These classes “wrap” the primitive data type value in an object. Hence the name “Wrapper Classes”.
  • All wrapper classes are immutable classes.

When to use Wrapper classes?

Here are some of the important points to remember when to use the wrapper classes.

  1. When you are working collections to store numeric values. Because collection objects can’t store primitive values.
  2. To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type.
  3. To convert String representation of primitive value into primitive data type.
  • In Java, For every primitive data type, there is corresponding wrapper class.

wrapperclasses_hierarchy

  • As shown in the above image, Number is the superclass for every numeric class such as Byte, Short, Integer, Long, Float, Double.
  • The number contains four important abstract methods which are implemented by its subclasses.
  • The below are the declarations of four abstract methods in Number class(abstract class) which are used to convert to a primitive value.

[code]
public abstract int intValue()
public abstract long longValue()
public abstract float floatValue()
public abstract double doubleValue()
[/code]

  • You don’t need to learn all classes for the exam.
  • Integer, Double, Boolean classes are on the exam.

In the following sections, I am going to write about most common wrapper classes and how to use them.

Integer

Here are some important points about the Integer class:

  • Integer class is in java.lang package since Java 1.0 version.
  • Number class is the superclass of Integer.
  • It implements Comparable,Serializable interfaces.
  • It is an immutable class.
  • The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.
  • In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

Creating Integer Object

Integer class has two constructors.

  • public Integer(int value)

It constructs a new Integer object that represents the specified int value.

  • public Integer(String s)throws NumberFormatException

It constructs a new Integer object that represents the int value indicated by the String parameter. The string is converted to an int value in exactly the manner used by the parseInt method for radix 10.
It throws NumberFormatException if the String does not contain a parsable integer.

  • You can also create Integer object without a constructor.

Example :

[code]
public class IntegerDemo {
public static void main(String[] args) {
Integer n1 = new Integer("5");
Integer n2 = new Integer(2);
Integer n3 = 4;
// Integer n4 = new Integer("A"); this statement generates NumberFormatException.
System.out.println(n1 + " " + n2 + " " + n3);//prints 5 2 4

}

}
[/code]

  • In the above program, you are storing primitive int value into Integer objects, it is called Boxing.

Important Integer methods

public static int parseInt(String s) throws NumberFormatException

  • This method converts the String representation of primitive integer value into a primitive integer value.
  • It throws NumberFormatException if the String does not contain a parsable integer.

Example :

[code]
ublic class IntegerDemo {

public static void main(String[] args) {

int n1 = Integer.parseInt("8");
// int n2 = Integer.parseInt("OCA"); This generates NumberFormatException.

System.out.println(n1);//prints 8

}

}
[/code]

  • public static String toHexString(int i): It returns a string representation of the integer argument as an unsigned integer in base 16.
  • public static String toOctalString(int i): It returns a string representation of the integer argument as an unsigned integer in base 8.
  • public static String toBinaryString(int i); It returns a string representation of the integer argument as an unsigned integer in base 2.

Example :

[code]
public class IntegerDemo {

public static void main(String[] args) {

String s1 = Integer.toHexString(8);
String s2 = Integer.toOctalString(8);
String s3 = Integer.toBinaryString(8);
System.out.println(s1 + " " + s2 + " " + s3); // prints 8 10 1000
}

}
[/code]

  • public static Integer valueOf(int i): It returns an Integer instance representing the specified int value.
  • public byte byteValue(): It returns the value of this Integer as a byte after a narrowing primitive conversion.
  • public double doubleValue(): It returns the value of this Integer as a double after a widening primitive conversion.
  • public float floatValue(): It returns the value of this Integer as a float after a widening primitive conversion.
  • public int intValue(): It returns the value of this Integer as an int.
  • public long longValue(): It returns the value of this Integer as a long after a widening primitive conversion.
    Example :

[code]
public class IntegerDemo {

public static void main(String[] args) {

Integer in = Integer.valueOf(8);
byte b = in.byteValue();
int i = in.intValue();
long l = in.longValue();
float f = in.floatValue();
double d = in.doubleValue();
System.out.println(in+" "+b+" "+i+" "+l+" "+f+" "+d);//It prints 8 8 8 8 8.0 8.0

}

}
[/code]

Autoboxing and Unboxing

Boxing conversions are that converting from primitive types to wrapper and wrapper classes to primitive types. You don’t have to explicitly do the conversions. The boxing conversions happen implicitly. This is part of the Java 5.0 features.

[code]
List<Integer> li = new ArrayList<Integer>();
li.add(8);// line 1
li.add(new Integer(5));// line 2
int n = li.get(1);// line 3
[/code]

  • At line1 you just typed 8 primitive value java will create Integer object and stores in the ArrayList object, this process is called Autoboxing.
  • At line2 you are creating the object. No Autoboxing here.
  • At line3 get method returns Integer object and that is converted into primitive int value when it is assigning to the int variable, this process is called Auto unboxing.

Double

Here are some important points about the Double class:

  • The double class is in java.lang package since Java 1.0 version.
  • Number class is the superclass of Double.
  • It implements Comparable,Serializable interfaces.
  • It is an immutable class.
  • The Double class wraps a value of the primitive type double in an object. An object of type Double contains a single field whose type is double.
  • In addition, this class provides several methods for converting a double to a String and a String to a double, as well as other constants and methods useful when dealing with a double.

Creating Double Object

The double class has two constructors.

  • public Double(double value)

It constructs a new Double object that represents the specified double value.

  • public Double(String s)throws NumberFormatException

It constructs a new Double object that represents the double value indicated by the String parameter. The string is converted to a double value in exactly the manner used by the parseInt method for radix 10.
It throws NumberFormatException if the String does not contain a parsable number.

  • You can also create a Double object without a constructor.

Example :

[code]
public class DoubleDemo {

public static void main(String[] args) {
Double n1 = new Double("5.0");
Double n2 = new Double(2.0);
Double n3 = 4.0;
// Double n4 = new Double("A"); this statement generates NumberFormatException.
System.out.println(n1 + " " + n2 + " " + n3);//prints 5.0 2.0 4.0

}

}
[/code]

  • In the above program, you are storing the primitive double value into Double objects, it is called Boxing.

Important Double methods

parseDouble

public static double parseDouble(String s) throws NumberFormatException

  • This method converts the String representation of number value into primitive double value.
  • It throws NumberFormatException if the String does not contain a parsable number.

Example :

[code]
public class DoubleDemo {

public static void main(String[] args) {

double n1 = Double.parseDouble("8.0");
double n2 = Double.parseDouble("2");
// double n3 = Double.parseDouble("OCA"); This generates NumberFormatException.

System.out.println(n1+" "+n2);//prints 8.0 2.0

}

}
[/code]

  • public static Double valueOf(double i): It returns a Double instance representing the specified double value.
  • public byte byteValue(): It returns the value of this Double as a byte after a narrowing primitive conversion.
  • public double doubleValue(): It returns the value of this Double as a double after a widening primitive conversion.
  • public float floatValue(): It returns the value of this Double as a float after a widening primitive conversion.
  • public int intValue(): It returns the value of this Double as an int.
  • public long longValue(): It returns the value of this Double as a long after a widening primitive conversion.
    Example :

[code]
public class DoubleDemo {

public static void main(String[] args) {

Double in = Double.valueOf(8);
byte b = in.byteValue();
int i = in.intValue();
long l = in.longValue();
float f = in.floatValue();
double d = in.doubleValue();
System.out.println(in+" "+b+" "+i+" "+l+" "+f+" "+d);//It prints 8.0 8 8 8 8.0 8.0

}

}
[/code]

Autoboxing and Unboxing

[code]
List<Double> li = new ArrayList<>();
li.add(8.0);// line 1
li.add(new Double(5));// line 2
double n = li.get(1);// line 3
[/code]

  • At line1 you just typed 8 primitive value java will create Double object and stores in the ArrayList object, this process is called Autoboxing.
  • At line2 you are creating the object. No Autoboxing here.
  • At line3 get method returns Double object and that is converted into primitive double value when it is assigning to double variable, this process is called Auto unboxing.

Boolean

Here are some important points about the Boolean class:

  • The Boolean class is in java.lang package since Java 1.0 version.
  • An object class is the superclass of Boolean.
  • It implements Comparable,Serializable interfaces.
  • It is an immutable class.
  • The Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.
  • In addition, this class provides several methods for converting a boolean to a String and a String to a boolean, as well as other constants and methods useful when dealing with a boolean.

Creating Boolean Object

A boolean class has two constructors.

  • public Boolean(boolean value)

It creates a Boolean object representing the value argument.

  • public Boolean(String s)

It creates a Boolean object representing the value true if the string argument is not null and is equal, ignoring case, to the string “true”. Otherwise, allocate a Boolean object representing the value false.

  • You can create Boolean using predefined fields in the Boolean class.

Example :

[code]
public class DoubleDemo {

public static void main(String[] args) {

Boolean b1 = new Boolean(true);
Boolean b2 = new Boolean("true");
Boolean b3 = new Boolean("false");
Boolean b4 = new Boolean("oca");
Boolean b5 = new Boolean("null");
Boolean b6 =Boolean.TRUE;
Boolean b7 = Boolean.FALSE;
System.out.println(b1+" "+b2+" "+b3+" "+b4+" "+b5+" "+b6+" "+b7);//prints true true false false false true false

}

}
[/code]

  • public static boolean parseBoolean(String s): It Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”.
  • public static Boolean valueOf(boolean b): It returns a Boolean instance representing the specified boolean value.
  • public boolean booleanValue(): It returns the value of this Boolean object as a boolean primitive.

Example :

[code]
public class DoubleDemo {

public static void main(String[] args) {

boolean b1 = Boolean.parseBoolean("true");
boolean b2 = Boolean.parseBoolean("oca");
Boolean b3 = Boolean.valueOf(false);
boolean b4 = b3.booleanValue();
System.out.println(b1 + " " + b2 + " " + b3 + " " + b4);// It prints true false false false
}

}
[/code]

Conclusion

person taking an online exam
Photo credit to onlineclassking.com

For OCAJP exam concentrate on Autoboxing and Auto unboxing, ParseXXX methods in three classes and possible ways to create the Boolean object. You have to remember the key concepts to answer all the questions related to the wrapper classes. Also, do a lot of practice questions to get more understanding of all the concepts.

Additional Resources

  • OCAJP 8 – Official Site
  • OCAJP Free Questions
  • How to prepare for OCAJP Exam?

 

 

Filed Under: Certifications Tagged With: OCAJP 8

How To Sign-Up for AWS Free Tier

December 1, 2016 by krishna Leave a Comment

AWS free tier is the free web services environment offered by Amazon for its first-time users. If you are new to the cloud computing world, then you must be aware that Amazon Web Services (AWS) is the leading cloud platform across the world. It has weak challenges from Microsoft and Google. So, there is a great number of opportunities for a career if you have good knowledge on AWS and prepare for the AWS certifications. In my previous article, I have explained how to prepare for AWS Solutions Architect Associate exam.

  • Try Now: Free AWS Questions for Solutions Architect Exam

Since everyone can not afford to pay for the cloud environment, Amazon has set up the free environment with a limited amount of bandwidth for those who can try for one year and then purchase the services from Amazon. This free tier is very useful for people who are learning first-time AWS technology. It is very simple to sign-up and gets started using the free tier.

aws-4

Note that Amazon would charge your credit card $1 at the time of signing up to validate if those credentials are correct. You will be charged only if you are using any of the non-free services. But, after one year Amazon will start charge cost from your registered credit card. So, delete your free account after your use if you are not planning to buy their services after one year.

How to Sign-Up for free tier?

aws-1

Please visit the site Sign-up for AWS Free Tier Account. This is the entry point for signing up for the free account. Here is the test that is provided on their website about the free account:

The Amazon Web Services (AWS) Free Tier is designed to enable you to get hands-on experience with AWS Cloud Services. The AWS Free Tier includes services with a free tier available for 12 months following your AWS sign-up date, as well as additional service offers that do not automatically expire at the end of your 12-month AWS Free Tier term.

Then you can click this link Register for Free Account.

Free Services

Here is the list of free services that are offered as part of the free account. Here I am listing only the name of the services and not providing the other details. If you want to know about the free tier offer, please visit this site.

  • Amazon EC2
  • Amazon S3
  • Amazon EFS
  • Amazon RDS
  • AWS IoT
  • Amazon EC2 Container Registry
  • AWS Lambda
  • Elastic Load Balancing
  • Amazon DynamoDB
  • Amazon CloudFront
  • Amazon Elastic Block Storage
  • Amazon ElastiCache
  • Amazon Redshift
  • AWS Data Pipeline
  • Amazon Elasticsearch Service
  • Amazon Cognito
  • AWS Device Farm
  • Amazon Mobile Analytics
  • Amazon SNS
  • AWS CodeCommit
  • AWS CodePipeline
  • AWS Key Management Service
  • Amazon CloudWatch
  • AWS Trusted Advisor
  • Amazon API Gateway
  • Amazon AppStream
  • Amazon Elastic Transcoder
  • Amazon SES
  • Amazon SQS
  • Amazon SWF
  • Amazon QuickSight

How to use AWS Free Services?

Once you have signed up for the free account, you will be able to see the list of services in your AWS console. Here, AWS Console refers to the place where you will see the list of all the services. You can directly click on any of the services and configure for your use. Also, you can look at the account settings and find how much is utilized. You also have look on the billing, some time without your knowledge you would have used the non-free services that would be billed on your credit card. The good news is that AWS is always charging you on the consumption. So, they charge very minimal cost.

Here is the snapshot of the AWS console.

aws-console

Additional Resources

Here is the list of additional resources that would help you to learn AWS.

  • Getting Guide from Amazon  – This is the official guide from Amazon website to get start learning AWS. There is a lot of videos to explore here.
  • AWS Certification – Here is the official site for AWS certification
  • AWS Certified Solutions Architect Associate exam practice questions
  • How did you prepare for AWS certification Exam
  • What are salary and career demand for the AWS developers

Summary

I hope this article would have helped you to understand how to enroll in the AWS free tier account. This is the first step towards learning AWS technology for the beginners. If you have any questions on learning AWS, please write your comments.

Filed Under: Certifications Tagged With: AWS Certification, AWS certification Exam, AWS Certified Solutions exam, AWS developers

OCAJP – Switch Statement Practice Questions

October 24, 2016 by krishna Leave a Comment

In my previous article, I have published how to prepare ArrayList topic for OCAJP exam. I am writing a series of articles on how to prepare for OCAJP certification exam. Also, read about the sample questions on Lambda Expressions.

Are you looking for mock exam questions to prepare for OCAJP 8 exam, please try these free mock exam practice questions for OCAJP exam?

OCAJP – Switch statement practice questions

1. Given

[code lang=”java”]
switch (a) {
case 1:
System.out.println("1");
break;
case 4:
System.out.println("4");
break;
case 2:
System.out.println("2");
break;
case 5:
System.out.println("5");
break;

}
[/code]

Which of the following statements can be inserted in place of //insert code here So that the above code compiles and runs?

  • A. int a = 1;
  • B. long a = 1;
  • C. Byte a = 1;
  • D. float a =1;
  • E. Integer a = new Integer(“1”);
  • F. compile time error.

2. Which of the following are valid statements about switch ?

  • A. switch expression of type int and case label value of type char are correct combination.
  • B. switch expression of type byte and case label value of type float are correct combination.
  • C. switch expression of type char and case label value of type byte are correct combination.
  • D. All combinations are wrong.

3. What is the output?

[code lang=”java”]
public class SwitchDemo {
public static void main(String args[]) {
boolean b = true;
switch (b) {
case true:
System.out.println("true");
break;
case false:
System.out.println("false");
default:
System.out.println("true false");

}

}
}
[/code]

  • A. true
  • B. false
  • C. true false
  • D. Compile time error
  • E. false

4. What data type of “value” is allowed so that it compiles and runs?

[code lang=”java”]
XXXX value = 50 ;
switch (value) {
case 32:
System.out.println("32");
break;
case 50:
System.out.println("50");
break;
case 150:
System.out.println("50");
break;
case 250:
System.out.println("50");

}
[/code]

  • A. int value = 50;
  • B. long value = 50;
  • C. char value = 50;
  • D. byte value = 50;
  • E. short value = 50;

5. What changes can be done to make this program compile and run successfully ?

[code lang=”java”]
public class SwitchDemo {

public static void main(String args[]) {

boolean value = true; //line 1

switch (value) {

case true: // line 2
System.out.println("true");
break;

default:
System.out.println("default");

}

}
}
[/code]

  • A. No change required.
  • B. Replace line 1 with String value = “true”;
  • C. Replace line 2 with the case “true” :
  • D. Replace both line 1 with String value = “true”; and line 2 with the case “true” :

6. What is the output?

[code lang=”java”]
public class SwitchDemo {
public static void main(String args[]) {
final int a = 5;
final int b = 6;
final int c;
c = 8;
switch (a) {
case a:
System.out.println("a");
break;
case b:
System.out.println("b");
break;
case c:
System.out.println("c");
break;
default:
System.out.println("none");

}

}
}
[/code]

  • A.
  • B. b
  • C. c
  • D. none
  • E. Compile time error.

7. What is the output?

[code lang=”java”]
String day = "Sun";
switch (day) {
case "Mon":
System.out.println("Monday");

case "Tue":
System.out.println("Tuesday");
break;
case "Sun":
System.out.println("Sunday");

default:
System.out.println("Friday");

}
[/code]

  • A. Monday
  • B. Tuesday
  • C. Sunday
  • D. Friday
  • E. Compile time error because String is not allowed.

Answers

1. Correct options : A,C,E. A, C, E are correct because int, byte, short, char and their wrapper classes are allowed as a data type of switch parameter data type. B, D are wrong options because long, float, double, boolean are not allowed by a switch statement.

2. Correct option: A. To answer this question you need to remember one rule about the switch.
Switch variable must able hold to all the case constants. For example, byte ranges from -128 to 127. So all case values must be within that range. A is correct because char values are in the range of it.

3. Correct option: D. D is correct because boolean data type is not allowed by the switch.

4. Correct options: A,C,E. A, C, E are correct because int, char, short can hold all case label values. B is wrong because long is not allowed. D is also wrong because byte range is -128 to 127.

5. Correct option: D. boolean data type is not allowed by the switch. So you need to change at line 1 and line 2.

6. Correct option: E. Because c is a final variable but it is initialized in the next line. So it is evaluated at runtime. so the whole expression evaluated at runtime. So it is not compiled time constant. It gives compile time error.

7. Correct option: D. Once case constant is matched, JVM will execute the associated case branch and subsequent code blocks if there is no break statement after first matched case.

References

If you are preparing for the OCAJP certification exam, then the following resources will be useful to you.

  • JavaBeat’s OCAJP Guide
  • OCAJP Mock Exams (Java Basics)
  • Lambda Expressions Practice Questions
  • How to prepare for OCAJP Certification Exam?
  • What are the good books for OCAJP Exam?

 

Filed Under: Certifications Tagged With: Lambda Expressions., OCAJP Certifications, OCAJP exam, Switch statement practice questions

OCAJP – Declare and use an ArrayList of a given type

October 17, 2016 by krishna Leave a Comment

This post is about the OCAJP exam objective “Declare and use an ArrayList of a given type“.You will be tested in the exam about various methods and syntax related to the ArrayList class. Here we would explain about the ArrayList class and its important methods. In my future posts, I would be explaining about some of the other concepts that are covered in the OCAJP exam. If you have any questions, please write your comments.

Are you looking for mock exam questions to prepare for OCAJP 8 exam, please try these free mock exam practice questions for OCAJP exam?

Here are some important points about the ArrayList class:

  • ArrayList is a class present in java until package since Java 1.2 version.
  • ArrayList is most widely used collections API for storing the list of objects.
  • It has one direct superclass i.e AbstractList
  • It has three direct subclasses(AttributeList,RoleList,RoleUnresolvedList).
  • It implements List,RandomAccess,Cloneable,Serializable.
  • It implements List, so you can store duplicate elements(objects) in the ArrayList.
  • It implements RandomAccess, so all methods run in constant time.
  • It is not synchronized.
  • It is a Resizable-array implementation of the List interface.
  • The size of the list is growing dynamically when more elements are added.
  • Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.
  • Insertion order is preserved. It means it stores the objects as you entered.
  • It can store any type of object if the ArrayList object is nongeneric. If it is generic, it stores particular type or subtype objects.
  • You can store null in the ArrayList object.

Creating ArrayList Object

The arraylist class has 3 constructors.

  • ArrayList()

It constructs an empty list with an initial capacity of ten.

  • ArrayList(Collection<? extends E> c)

It constructs a list containing the elements of the specified collection, in the order, they are returned by the collection’s iterator. It throws NullPointerException if c is null.

  • ArrayList(int initialCapacity)

It constructs an empty list with the specified initial capacity. It throws IllegalArgumentException if the specified initial capacity is negative.

Example :

import java.util.ArrayList;
import java.util.LinkedList;

public class ArrayListCreate {
	public static void main(String[] a) {

		ArrayList al1 = new ArrayList<>();// capacity is 10
		ArrayList al2 = new ArrayList<>(20);// capacity is 20
		LinkedList ll = new LinkedList<>();
		ArrayList al3 = new ArrayList<>(ll);// capacity may greater than
													// number of objects

	}

}

ArrayList Methods

In the subsequent sections, we would look at the various important ArrayList class’s methods and how to use them. These methods are very important for preparing OCAJP exam, in the exam, you will be tested to answer the questions that are related to operations using the ArrayList methods.

add(),addAll()

public boolean add(E e)

  • It appends the specified element to the end of this list.

public void add(int index,E element)

  • It inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
  • It throws IndexOutOfBoundsException if the index is less than zero or greater than the size of ArrayList.

public boolean addAll(Collection<? extends E> c)

  • It appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection’s Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress.

Example :

import java.util.ArrayList;

public class ArrayListAdd {
	public static void main(String[] a) {
			
		ArrayList a1 = new ArrayList<>();
		ArrayList a2 = new ArrayList<>();
		a1.add("OC");
		a1.add("JP");
		a1.add(1,"A");
		a1.add(3,"8");
		a1.add(4,"8");	
		a2.add("OC");
		a2.add("P8");
		System.out.println(al);//prints [OC, A, JP, 8, 8]
		a1.addAll(a2);
		System.out.println(al);//prints [OC, A, JP, 8, 8, OC, P8]

	}

}

isEmpty() and size()

public boolean isEmpty()

  • It returns true if this list contains no elements.

public int size()

  • It returns the number of elements in this list.

Example :

import java.util.ArrayList;

public class ArrayListEmpty {
	public static void main(String[] a) {
			
		ArrayList al = new ArrayList<>();
		al.add("OC");
		al.add("JP");
		al.add(1,"A");
		al.add(3,"8");
		al.add(4,"8");	
		System.out.println(al);//prints [OC, A, JP, 8, 8]
		System.out.println(al.isEmpty());//prints false
		System.out.println(al.size());//prints 5
	}

}

get(),set()

public E get(int index)

  • It returns the element at the specified position in this list.
  • It throws IndexOutOfBoundsException if the index is less than zero or greater than the size of ArrayList

public E set(int index,E element)

  • It replaces the element at the specified position in this list with the specified element.
  • It throws IndexOutOfBoundsException if the index is less than zero or greater than the size of ArrayList.

Example :

import java.util.ArrayList;

public class ArrayListGet {
	public static void main(String[] a) {
			
		ArrayList al = new ArrayList<>();
		al.add("OC");
		al.add("JP");
		al.add(1,"A");
		al.add(3,"8");
		al.add(4,"8");	
		System.out.println(al);//prints [OC, A, JP, 8, 8]
		al.set(1, "P");
		System.out.println(al);//prints [OC, P, JP, 8, 8]
		System.out.println(al.get(2));//prints JP
		
	}

}

remove(),clear()

public boolean remove(Object o)

  • It removes the first occurrence of the specified element from this list and returns true if it is present. If the list does not contain the element, it is unchanged and returns false.

public E remove(int index)

  • It removes the element at the specified position in this list and returns that element. Shifts any subsequent elements to the left (subtracts one from their indices).
  • It throws IndexOutOfBoundsException if the index is less than zero or greater than the size of ArrayList.

public void clear()

  • It removes all of the elements from this list.

Example :

import java.util.ArrayList;

public class ArrayListRemove {
	public static void main(String[] a) {
			
		ArrayList al = new ArrayList<>();
		al.add("OC");
		al.add("JP");
		al.add(1,"A");
		al.add(3,"8");
		al.add(4,"8");	
		System.out.println(al);//prints [OC, A, JP, 8, 8]
		al.remove("A");
		al.remove(3);
		System.out.println(al);//prints [OC, JP, 8]
		al.clear();
		System.out.println(al);//prints []
		
	}

}

subList()

public List subList(int fromIndex,int toIndex)

  • It returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. If fromIndex and toIndex are equal, the returned list is empty. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
  • It throws IndexOutOfBoundsException if fromIndex is less than Zero or toIndex is greater than ArrayList size.
  • It also throws IllegalArgumentException if fromIndex is greater than toIndex.

Example :

public class ArrayListSubList {
	public static void main(String[] a) {
			
		ArrayList a1 = new ArrayList<>();
		
		a1.add("OC");
		a1.add("JP");
		a1.add(1,"A");
		a1.add(3,"8");
		a1.add(4,"8");	
		
		System.out.println(a1.subList(1, 3));//prints [A, JP]
		

	}

}

contains(),indexOf(),lastIndexOf()

public boolean contains(Object o)

  • It returns true if this list contains the specified element otherwise returns false.

public int indexOf(Object o)

  • It returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element.

public int lastIndexOf(Object o)

  • It returns the index of the last occurrence of the specified element in this list, or -1 if this list does not contain the element.

Example :

public class ArrayListContain {
	public static void main(String[] a) {
			
		ArrayList al = new ArrayList<>();
		al.add("OC");
		al.add("JP");
		al.add(1,"A");
		al.add("OC");
		al.add(3,"8");
		al.add(4,"8");	
		System.out.println(al);//prints [OC, A, JP, 8, 8]
		System.out.println(al.contains("A"));//prints true
		System.out.println(al.indexOf("OC"));//prints 0
		System.out.println(al.lastIndexOf("OC"));//prints 5
	}

}

Conclusion

For the OCAJP, Make sure you have a clear understanding about ArrayList methods. Remember the important ArrayList class methods declarations and their functionality. Be able to identify the correct output when multiple methods are chaining. The above all are the important methods for OCAJP.

References

If you are preparing for the OCAJP certification exam, then the following resources will be useful to you.

  • JavaBeat’s OCAJP Guide
  • OCAJP Mock Exams (Java Basics)
  • How to prepare for OCAJP Certification Exam?
  • What are the good books for OCAJP Exam?

 

Filed Under: Certifications Tagged With: ArrayList, OCAJP 8, OCAJP exam, syntax

OCAJP – Lambda Practice Questions for Preparing OCAJP 8 Certification

October 6, 2016 by krishna Leave a Comment

Lambda Practice Questions
Photo credit to AC4 Consultoria

In this post, I am going to write down few OCAJP 8 mock exam question examples with good explanations. We have earlier explained about the Lambda and Predicate expressions with few sample questions. If you are preparing for the OCAJP 8 exam, then it is most likely that you have to practice more for the Java 8 specific topics since they are relatively new topics in the exam. They might test you with a different combination of syntax and ask you to choose the correct answers.

Here are the 9 questions for OCAJP 8 exam that will be useful for your OCAJP Java Certification Preparation. If you have any questions, please write it in the comments section. If you are interested in practicing more questions, please consider buying any of the popular OCAJP Practice Exam Simulators available in the market. They offer questions that are very much relevant to the real exams.

OCAJP 8 Exam Objective

Here is the exam objective for preparing the OCAJP exam:

  • OCAJP 8 Exam expects you to recognize valid, invalid lambda expressions. It doesn’t ask you to write the lambda expressions.

What is Lambda Expression?

Lambda Expressions in Java
Photo credit to YouTube

Here is the overview or definition of Lambda expression in Java 8 if you are not aware this concepts. before you read the mock questions, please understand the Lambda expression in Java 8.

A lambda expression is an anonymous method with more compact syntax that also allows the omission of modifiers, return type, and in some cases parameter types as well. Before lambda expressions, the anonymous methods are written inside the anonymous classes which are many lines of compare to the single line lambda expression.

1) Which are true about the functional interface?

  • A. It has exactly one method and it must be abstract.
  • B. It has exactly one method and it may or may not be abstract.
  • C. It must have exactly one abstract method and may have any number of default or static methods.
  • D. It must have exactly one default method and may have any number of abstract or static methods.
  • E. It must have exactly one static method and may have any number of default or abstract methods.

2) Given

[code]
interface Test {
public void print( );
}
[/code]

Which are valid lambda expressions (select 2 options)?

  • A. ->System.out.println(“Hello world”);
  • B. void -> System.out.println(“Hello world”);
  • C. ( ) -> System.out.println(“Hello world”);
  • D. ( ) ->{ System.out.println(“Hello world”); return; }
  • E. (void ) -> System.out.println(“Hello world”);

3) Which lambda can replace the MyTest class to return the same value? (Choose all that apply)

[code]
interface Sample {
String change(int d);
}
class MyTest implements Sample {
public String change(int s) {
return "Hello";
}
}
[/code]

  • A. change((e) -> “Hello” )
  • B. change((e) -> {“Hello” })
  • C. change((e) -> { String e = “”; “Hello” });
  • D. change((e) -> { String e = “”; return “Hello”; });
  • E. change((e) -> { String e = “”; return “Hello” });
  • F. change((e) -> { String f = “”; return “Hello”; });

4) What is the result ?

[code]
1: import java.util.function.*;
2:
3: public class Student {
4: int age;
5: public static void main(String[] args) {
6: student p1 = new Student();
7: p1.age = 1;
8: check(p1, p -&amp;gt; p.age &amp;lt; 5);

9: }
10: private static void check(Student s, Predicate&amp;lt;Student&amp;gt; pred) {
11: String result = pred.test(s) ? "match" : "not match";
12: System.out.print(result);
13: } }
[/code]

  • A. match
  • B. not match
  • C. Compiler error on line 8.
  • D. Compiler error on line 10.
  • E. Compiler error on line 11.
  • F. A runtime exception is thrown.

5) What is the output?

[code]
1: interface Jump {
2: boolean isToLong(int length, int limit);
3: }
4:
5: public class Climber {
6: public static void main(String[] args) {
7: check((h, l) -&amp;gt; h.append(l).isEmpty(), 5);
8: }
9: private static void check(Jump j, int length) {
10: if (j.isTooLong(length, 10))
11: System.out.println("too high");
12: else
13: System.out.println("ok");
14: }
15: }
[/code]

  • A. ok
  • B. too high
  • C. Compiler error on line 7.
  • D. Compiler error on line 10.
  • E. Compiler error on a different line.
  • F. A runtime exception is thrown.

6) What can be inserted in the code below so that it will true when run?

[code]
class Test {
public static boolean check( List l , Predicate&amp;lt;List&amp;gt; p ) {
return p.test(l) ;
}
Public static void main(String[] args) {
boolean b = // write code here ;
System.out.println(b);
}
}
[/code]

Select 2 options

  • A. check(new ArrayList( ), al -> al.isEmpty( ) );
  • B. check(new ArrayList( ), ArrayList al -> al.isEmpty( ) );
  • C. check(new ArrayList( ), al -> return al.size( ) == 0 );
  • D. check(new ArrayList( ), al -> al.add(“hello”));

7. Given

[code]
class Test {
int a ;
Test( int a ) {
This.a = a;
}
}
And the following code fragment
public void filter (ArrayList&amp;lt;Test&amp;gt; al,Predicate&amp;lt;Test&amp;gt; p) {
iterator&amp;lt;Test&amp;gt; i = al.iterator( );
while(i.hasNext( ) ) {
if(p.test(i.next( ) ) {
i.remove( );
} }
—-
ArrayList&amp;lt;Test&amp;gt; l = new ArrayList&amp;lt;Test&amp;gt;( );
Test t = new Test(5); l.add(t);
t= new Test(6); l.add(t);
t=new Test(7); l.add(t);
//Insert method call here
System.out.println(l);
[/code]

Which of the following options print [5 7] ?

  • A. filter(al,t->t.a%2==0 ) ;
  • B. filter(al, (Test y)->y.a%2==0);
  • C. filter(al, (Test y)->y.a%2);
  • D. filter(al, y-> return y.a%2==0);

8. Which are true about java.util.function.Predicate ?

  • A. It is an interface that has one method with a declaration like-
    public void test(T t)
  • B. It is an interface that has one method with a declaration like-
    public boolean test(T t)
  • C. It is an interface that has one method with a declaration like-
    public boolean test(T t)
  • D. It is an abstract class that has one method with a declaration like-
    public abstract boolean test(T t)
  • E. It is an abstract class that has one method with a declaration like-
    public abstract void test(T t)

9. Given

[code]
class Test {
int a ;
Test( int a ) {
This.a = a;
}
}
And the following code fragment
public void filter (ArrayList&amp;lt;Test&amp;gt; al,Predicate&amp;lt;Test&amp;gt; p) {
for(Test t : al) {
if(p.test(t))
System.out.println(t.a)
} }
—
ArrayList&amp;lt;Test&amp;gt; l = new ArrayList&amp;lt;Test&amp;gt;( );
Test t = new Test(5); l.add(t);
t= new Test(6); l.add(t);
t=new Test(7); l.add(t);
//Insert method call here
[/code]

Which of the following options print 7?

  • A. filter(al, (Test y) -> { return y.a>6 ; });
  • B. filter(al, (Test y) -> { return y.a>6 });
  • C. filter(al, ( d) -> return d.a>6) ;
  • D. filter(al, d -> d.a>6) ;

Answers

1) Correct option : C

Functional interface must have exactly one abstract method and may have any number of default or static methods.

2) Correct options : C,D

Method doesn’t take any parameters , lambda expression should contain parenthesis in the parameter list of lambda expression. Method doesn’t return anything, so body part should not return anything.

3) Correct options : A, F.

Option B is incorrect because it does not use the return keyword. Options C, D and E are incorrect because the variable e is already in use from the lambda and cannot be redefined. Additionally, option C is missing the return keyword and option E is missing the semicolon.

4) Correct option: A.

This code is correct. Line 8 creates a lambda expression that checks if the age is less than 5. Since there is only one parameter and it does not specify a type, the parentheses around the type parameter are optional. Line 10 uses the Predicate interface, which declares a test() method

5) Correct option: C.

The interface takes two int parameters. The code on line 7 attempts to use them as if one is a StringBuilder. It is tricky to use types in a lambda when they are implicitly specified. Remember to check the interface for the real type.

6) Correct options : A,D

B is incorrect because parenthesis is missing for parameter and ArrayList is incorrect data type for the parameter. C is incorrect because curly braces are mandatory to return keyword.

7) Correct option: B

Option A is syntactically correct but it gives compile time error because t variable within the same scope and can’t be declared two times. C is incorrect because it returns the int, but Predicate method will return boolean. D is incorrect because curly braces are mandatory when the return is being used in the lambda expression.

8) Correct option: B

To answer this question you need to remember Predicate method declaration
Follow this link to know more about Predicate: https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html

9) Correct options : A,D

B is incorrect because the semicolon is missing after the return statement. C is incorrect curly braces are mandatory when the return is being used.

I hope this questions would be useful for preparing OCAJP 8 exam. If you have any questions in preparing for OCAJP exam, please write it in the comments section. We are happy to help you in passing the exam.

Filed Under: Certifications Tagged With: Lambda and Predicate expressions, Lambda Expression, OCAJP Certifications, OCAJP Practice Exam Simulators

OCAJP 8 – Java 8 Date Time API

April 7, 2015 by Krishna Srinivasan Leave a Comment

One of the new and noteworthy introduction in the Java 8 version is update of the Date Time API. Since the initial version of the Java packages, there is no standard API for calculating the date and time data. In the previous versions, there are two packages java.util and java.sql defines the date and time API with different features. Which makes cumbersome for the developers to understand when to use the suitable classes for manipulating date and time data. Java 8 introduces a new package java.time with lots of data time classes for the date manipulation. This would replace the legacy classes.

This tutorial is helpful for preparing the date and time classes as part of the OCAJP 8 certification exam. I have covered all the classes mentioned in the exam topics for date and time API. Objective for certification is “Create and manipulate calendar data using classes from java.time.LocalDateTime?, java.time.LocalDate?, java.time.LocalTime?, java.time.format.DateTimeFormatter?, java.time.Period”.

This tutorial explains the following APIs with simple examples.

  1. java.time.LocalDate
  2. java.time.LocalTime
  3. java.time.LocalDateTime
  4. java.time.Period
  5. java.time.format.DateTimeFormatter

java.time.LocalDate

This is a immutable class with the default date format of yyyy-MM-dd. The functionality provided by this class is similar to the one that is provided by java.sql.Date API. java.util.Date provides method now() to get the current date. Note that this method has the overloaded verion to get the current date in the specific zone by passing the ZoneId as the argument to method now().

Let’s look at an example:

[code lang=”java”]
package javabeat.net;

import java.time.LocalDate;
import java.time.ZoneId;
/**
* LocalDate Examples
* @author krishna (www.javabeat.net)
*
*/
public class LocalDateExample {
public static void main(String[] args) {
LocalDate localDateToday = LocalDate.now();
System.out.println("Today’s Date : "+localDateToday);
LocalDate localDateZone = LocalDate.now(ZoneId.of("America/Los_Angeles"));
System.out.println("Today’s Date at Zone America/Los_Angeles : "+localDateZone);
}
}
[/code]

Output for the above program:

[code]
Today’s Date : 2015-04-06
Today’s Date at Zone America/Los_Angeles : 2015-04-06
[/code]

java.time.LocalTime

java.time.LocalTime class is similar to LocalDate, it povides human readable time in the format of hh:mm:ss.zzz. This class also provides the ZoneId support for getting the time for the given ZoneId.

Let’s look at an example for LocalTime class.

[code lang=”java”]
package javabeat.net;

import java.time.LocalTime;
import java.time.ZoneId;

/**
* LocalTime Example
* @author krishna (www.javabeat.net)
*
*/
public class LocalTimeExample {
public static void main(String[] args) {
LocalTime currentTime = LocalTime.now();
System.out.println("Current Time : " + currentTime);
LocalTime localTimeZone = LocalTime.now(ZoneId.of("America/Los_Angeles"));
System.out.println("Current Time at America/Los_Angeles : " + localTimeZone);
}
}
[/code]

Output for the above program:

[code]
Current Time : 20:47:00.725
Current Time at America/Los_Angeles : 08:17:00.729
[/code]

java.time.LocalDateTime

LocalDateTime is an immutable object that presents a date-time. The default format for the date-time value is yyyy-MM-dd-HH-mm-ss.zzz. LocalDateTime class provides a factory method that takes LocalDate and LocalTime arguments to create LocalDateTime instance.

Let’s look at a simple example.

[code lang=”java”]
package javabeat.net;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;

public class LocalDateTimeExample {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current Date Time : " + localDateTime);

LocalDateTime today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
System.out.println("Current DateTime="+today);

LocalDateTime localDateTimeZone = LocalDateTime.now(ZoneId.of("America/Los_Angeles"));
System.out.println("Current Date Time at America/Los_Angeles : " + localDateTimeZone);
}
}
[/code]

Out for the above program:

[code]
Current Date Time : 2015-04-06T21:52:55.996
Current DateTime=2015-04-06T21:52:55.997
Current Date Time at America/Los_Angeles : 2015-04-06T09:22:56.004
[/code]

java.time.format.DateTimeFormatter

Before Java 8, the standard Java approach for formatting the dates was using DateFormat and SimpleDateFormat. With Java 8, the preferred date/time classes are not longer maintained in the java.util package and the new date/time handling classes are part of java.time package. In the same way, preferred date/time formatting classes are no longer in the java.text package and the new formatting classes are found in java.time.format package.

With Java 8, DateTimeFormatter class will be primarily used for formatting date/time data for Java application. This class also part of OCAJP 8 exam topics. The DateTimeFormatter class provides ofPattern methods to provide an instance of DateTimeFormatter based on the given date/time pattern as String.

Let’s look at a simple example.

[code lang=”java”]
package javabeat.net;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterExample {
public static void main(String[] args) {
DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter
.ofPattern("yyyy/MM/dd HH:mm:ss z");
DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter
.ofPattern("yyyy/MM/dd");
DateTimeFormatter dateTimeFormatter3 = DateTimeFormatter
.ofPattern("dd/MMM/YYYY");
ZonedDateTime zonedDateTime = ZonedDateTime.now();
String formatter1 = dateTimeFormatter1.format(zonedDateTime);
String formatter2 = dateTimeFormatter2.format(zonedDateTime);
String formatter3 = dateTimeFormatter3.format(zonedDateTime);
System.out.println(formatter1);
System.out.println(formatter2);
System.out.println(formatter3);
}
}
[/code]

Output for the above program will be:

[code]
2015/04/07 07:14:51 IST
2015/04/07
07/Apr/2015
[/code]

java.time.Period

Period provides the quantity or amount of time in terms of years, months and days. If you want to find the exact period between two dates, Period class would provide you the details with the in-built methods. This class is immutable and thread-safe.

Let’s look at a simple example that demonstrates how to use Period class.

[code lang=”java”]
package javabeat.net;

import java.time.LocalDate;
import java.time.Period;

public class PeriodExample {
public static void main(String[] args) {
LocalDate localDate1 = LocalDate.of(2014, 03, 03);
LocalDate localDate2 = LocalDate.of(2015, 07, 01);
Period period = Period.between(localDate1, localDate2);
System.out
.println("03-March-2014 to 01-July-2015 :Years ("
+ period.getYears() + "), Months(" + period.getMonths()
+ "), Days(" + period.getDays() + ")");
}

}
[/code]

Output for the above program will be:

[code]
03-March-2014 to 01-July-2015 :Years (1), Months(3), Days(28)
[/code]

Sample Mock Exams – OCAJP 8 Date Time Classes

1. Which of the following package declares the class DateTimeFormatter?

  1. java.util
  2. java.sql
  3. java.lang
  4. java.time.format

Correct Answer : 4. java.time.format

Explanation: java.time.format is the new package introduced in Java 8 for declaring the date/time formatting APIs. The other classes declared inside this package is DateTimeFormatterBuilder and DecimalStyle.

2. Please choose the correct class name(s) which is declared inside the package java.time.

  1. Date
  2. LocalTime
  3. Period
  4. DateTime
  5. LocalDateTime

Correct Answer : 2,3 & 5 (LocalTime, Period and LocalDateTime)

Explanation : Date is defined under the package java.util and DateTime is wrong class name.

3. Read the below syntax and choose the correct option that is valid data for “arg3”

LocalDate localDate = LocalDate.of(arg1, arg2, arg3);

  1. Month
  2. Year
  3. Day
  4. Syntax is not correct

Correct Answer : 3. Day

Explanation : LocalDate.of(YEAR,MONTH,DAY) returns the LocalDate object based on the parameters passed to this method.

Filed Under: Certifications Tagged With: OCAJP 8

OCAJP 8 – Lambda Expression / Predicate

April 5, 2015 by Krishna Srinivasan Leave a Comment

This tutorial is a preparation material for OCAJP certification exam. This covers the objective 9.5 in the OCAJP 8 exam topics (Write a simple Lambda expression that consumes a Lambda Predicate expression). The mock exams that would appear on the real exams could be simpler than the sample mock exams in this tutorial.

Java is purely object oriented programming. Java treats everything in the form of object. Functions are not given the highest importance in Java programming, thanks to the popularity of the functional programmings like JavaScript. Java 8 takes the first step towards introducing the functional programming with Lambda expressions.

Lambda Expressions

Some of the key points about the lambda expressions.

  • There is no need to declare the type of the parameters, compiler can implicitly decide the type from the value of the parameters.
  • There is no need to use parenthesis for a single parameter. If we are using the multiple parameters, then it should be enclosed with parenthesis.
  • If the lambda expression body contains a single statement, then there is no need to use the curly braces for the statement block. It is required if there is more than one statements in the block.
  • Lambda expressions are introduced primarily to define inline implementation of a functional interfaces i.e. an interface with a single abstract method only.
  • Lambda expression replaces the need of anonymous class and gives a very simple and powerful functional programming capability to Java programming language.

In Java, before Java 8 version the syntax for using the anonymous class as below:

[code lang=”java”]
package javabeat.net;

public class AnonymousExample {
public static void main(String[] args) {
SomeListener listener = new SomeListener() {

@Override
public void action() {
System.out.println("Action Performed");

}
};
listener.action();
}
}
interface SomeListener {
void action();
}
[/code]

If you look at the above code, SomeListener is a functional interface (because it declares only one abstract method) and used as anonymous class in the example. We have to declare the inline implementation of that class for creating the instance that will used for calling the methods action(). The above code could be simplified using the lambda expressions as below:

[code lang=”java”]
package javabeat.net;
public class AnonymousExample{
public static void main(String[] args) {
SomeListener listener = () -> System.out.println("Action Performed");
listener.action();
}
}

interface SomeListener {
void action();
}
[/code]

Lambda expression has three parts.

ocajp lambda syntax

  • Argument List is the parameters of the method. This method must match the parameters in the target functional interface. Also type of the parameters can be omited.
  • Arrow Token informs compiler that this expression is a lambda notation and parse it accordingly.
  • Body is the actual implementation of the functional method. Either this could be a single expression, single statement without a curly braces or multiple statements with curly braces.

Predicate with Lambda Expression

Predicate is a functional interface introduced as part of the Java 8 version under the package java.util.function. The following are some of the key points about the Predicate interface.

  • Predicate is used for assigning a lambda expression.
  • It is a functional interface.
  • Predicate interface defines 4 default methods and one functional method(abstract method).
  • Predicates represents single argument functions that return a boolean value.
  • Predicates can be chained together using and, or and negate to filter the data.
  • Four methods in the Predicate interface is and, or, isEqual, negate and test.
  • test(T t) in the predicate interface returns the boolean value

Here is a simple example that demonstrates the power of using predicate with lambda expressions.

[code lang=”java”]
package javabeat.net;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PredicateExample {
public static void main(String[] args) {
Child child1 = new Child(3);
Child child2 = new Child(2);
Child child3 = new Child(7);
Child child4 = new Child(10);
Child child5 = new Child(6);
Child child6 = new Child(9);
Child child7 = new Child(8);
List<Child> childs = Arrays.asList(new Child[] { child1, child2,
child3, child4, child5, child6, child7 });
List<Child> filtered = ChildPredicates.filterChilds(childs,
ChildPredicates.filterByAge(8));
for (Child child : filtered) {
System.out.println(child.getAge());
}
}
}

class ChildPredicates {
static Predicate<Child> filterByAge(int x) {
return a -> a.getAge() > x;
}

static List<Child> filterChilds(List<Child> childs,
Predicate<Child> predicate) {
return childs.stream().filter(predicate)
.collect(Collectors.<Child> toList());
}
}

class Child {
int age;

public Child(int age) {
this.age = age;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}
}
[/code]

In the above example, we are creating predicates for filtering the child with condition as age. If we don’t have the feature of the predicate and lambda, we may have to write the logic for checking the each condition and write a method. Also stream API provide the filter() method that takes the predicate as argument and evaluate the lambda expression.

Sample Mock Exam For Lambda Expressions and Predicate

1. What will be the output of the below program?

[code lang=”java”]
package javabeat.net;

public class LambdaMock1 {
static final int k = 20;
interface Inter{
int method(int x);
}
public static void main(String[] args) {
Inter inter = (x) -> k + 10;
System.out.println(inter.method(20));
}
}
[/code]

Answers are:

  1. compiler error
  2. 30
  3. If you remove final keyword for variable k, the program will compile fine
  4. None of the above

Correct Answer : 30

Explanation:

  1. Final variable can be accessed inside a lambda expression
  2. There is no error in the lambda syntax in the above program

2. Which of the following are valid syntax for lambda expressions?

  1. () -> System.out.println(“Lambda”);
  2. () -> {System.out.println(“Lambda”);};
  3. () <- System.out.println();
  4. () <- {System.out.println();};

Correct Answer : 1,2

Explanation: The correct notation for lambda expression is ->. 1 & 2 uses the correct notaion with curly braces and wothout curly braces.

3. Return keyword in lambda expression is optional when body has a single expression to return the value. State whether the above statements are true?

  1. True
  2. False

Correct Answer: 1

Explanation: Compiler automatically returns value if body has a single expression to return the value. Curly Braces are required to indicate that expression returns a value.

4. Predicate is not a functional interface. Is the above statement true/false?

  1. True
  2. False

Correct Answer: 2. False

Explanation: Predicate is a functional interface

5. State that if the below statement is correct in syntax.Assume that s is not delcared anywhere in the program.
Predicate predicate = (s)->s.equals(“string”);

  1. Incorrect. There will be complier error (s is not delclared)
  2. The above statement would compile and run without any error.

Correct Answer: 2

Explanation: The above statement would compile and run without any error. It is a lambda expression and we need not declare the variable s since it is used inside lambda expressions.

6. What is the return type of the method test(T t) in the Predicate functional interface?

  1. char
  2. boolean
  3. String
  4. int

Correct Answer: 2

Explanation: test(T t) is abstract method in the Predicate interface and returns the boolean type.

7. What will be the output for the below program:

[code lang=”java”]
package javabeat.net;

import java.util.function.Predicate;

public class PredicateExample {
public static void main(String[] args) {
Predicate<Integer> greaterThanTen = (var) -> var > 10;
System.out.println(greaterThanTen.test(10));
}
}
[/code]

  1. true
  2. false
  3. compiler error
  4. run time exception

Correct Answer: false

Explanation: This program will cimpile properly and evaluate the lambda expression to check if it is greater than 10 for value passed as argument.

Filed Under: Certifications Tagged With: OCAJP

OCAJP (Oracle Certified Associate Java Programmer)

March 31, 2015 by Krishna Srinivasan Leave a Comment

This page is regularly updated with latest information on OCAJP exam and provides comprehensive details about the Oracle Certified Associate Java Programmer Exam 1. If you are not finding the information which you are looking for or if you want to purchases certification exam kit, please feel free to send a mail at sales@javabeat.net.

What is OCAJP Exam?

Oracle′s Java SE Programmer I (OCAJP) Exam to achieve Oracle Certified Associate, Java SE Programmer Certification. This is the entry level of Java Certification. For every new version of Java, this exam will be updated with the new changes in the Java technology. The latest version of this certification is Java SE 8 Programmer I (1Z0-808). This certification doesn’t require much experience for passing the exam. It only checks the basic knowledge on the Java programming who are inspiring to start their career in Java technology.

Java Certification Path

OCAJP Exams

The following are the list of OCAJP exams conducted by Oracle. These exams are revised every time when there is a new version of Java is released in the market. Also any version which is more out dated to industry will be decommissioned and removed from the certification plans.

  • Oracle Certified Associate, Java SE 8 Programmer (1Z0-808)
  • Oracle Certified Associate, Java SE 7 Programmer (1Z0-803) (OCAJP 7 Exam Objectives / Syllabus)
  • Oracle Certified Associate, Java SE 5/SE 6 Programmer (1Z0-850)

What is New in OCAJP 8?

Most of the cases each revision of the certification would not bring the drastic changes to the certification topics list. The changes would be minimal and it will add up only the prominent features in the new version of the Java release. Similarly, OCAJP 8 is not much different from the OCAJP 7 exam, there are only few new topics introduced as part of this revision.  Here is the new topics that is part of the OCAJP 8 exam.

[table id=4 /]

Frequently Asked Questions  (FAQs)

How many OCAJP 7 exam questions?

There are total 70 questions will be asked in the OCAJP. It is the entry level example in the Java Certification path. The questions which are asked as part of this exam is fundamentals of Java and not much programming or real time experience is required to answer the questions. Many of the questions will be the programming examples.

Time duration for the OCAJP exam

120 minutes is the duration of this exam, so you need to attend all the 70 questions in this time limit to get good score in your certification exam.

What is the cost of the exam?

The cost would vary for each country and also the prometric centers would offer discount for special promotions. However, the actual cost of this certification exam mentioned in the oracle website is US$ 245. In India it would cost around Rs. 9000. Note that oracle is running a promotion of 20% discount for all the Java certification to celebrate it’s 15th year.

Passing score for the OCAJP exam

The passing score is 63%. To successfully finish OCAJP certification you need to get 63% of marks in 1Z0-803 Exam.

What is the difficulty level of this exam?

It is the first level of certification in the Oracle Java certification path. This exam checks the very basic knowledge on the Java programming which is required for the entry level programmers. Asking the questions related to the fundamentals like correct syntax, various keywords used in Java and its usage, etc. Look at the topics covered under this exam:

  1. Java Basics (Mock Exam Questions)
  2. Working With Java Data Types
  3. Using Operators and Decision Constructs
  4. Creating and Using Arrays
  5. Using Loop Constructs
  6. Working with Methods and Encapsulation
  7. Working with Inheritance
  8. Handling Exceptions

Where to find the test center details?

These exams are conducted by the certified prometric or test centers across the world. These centers are tied up with the Oracle for downloading the questions into their authorized test centers. You can find the details of the nearby centers here.

Can I write OCPJP Exam without writing OCAJP Exam?

One of the most frequently asked questions about certification is can I write OCPJP Exam without writing OCAJP Exam?. The answer to this question is depends on whether you have already written any exams or you are preparing for upgrade Exam. So, I have decided to provide more details about the different scenarios when you require OCAJP exam and when it is not required. If you are not convinced with this explanation, please drop a comment or send a mail to sales@javabeat.net.

  • If you are appearing for the Java 7 Exam first time and have not completed any Java certifications, then writing OCAJP is compulsory and once you clear that exam you will be eligible to write OCPJP Exam.
  • If you are planning to write upgrade exam, for example you have already written Java 5 or Java 6 exam, then you need not go through the OCA path. You can directly write the OCPJP Exam.
  • If you are appearing for Java 6 or prior versions, then you need not take OCA exams. The prerequisite of OCA exam is applicable only from Java 7 on wards. Note that Java certifications are available only form Java 5 version (Earlier versions are decommissioned from the certification path)
  • The exam code is different for upgrade exams.

Exam Details – OCAJP 8

  • Exam Number : 1Z0-808
  • Certification Name : Oracle Certified Associate, Java SE 8 Programmer
  • Duration : 150 minutes
  • Number of Questions : 77
  • Passing Score : 65%
  • Format : Multiple Choice
  • Price : It varies for each country and location. Please check with your nearest prometric centers.

Exam Details – OCAJP 7

  • Exam Number : 1Z0-803
  • Certification Name : Oracle Certified Associate, Java SE 7 Programmer
  • Duration : 120 minutes
  • Number of Questions : 70
  • Passing Score : 63%
  • Format : Multiple Choice
  • Exam Price : It varies for each country and location. Please check with your nearest prometric centers.

Free Mock Exams

  • Java Basics
  • OCAJP – Pass by Value or Pass by Reference
  • OCAJP – Static Methods and Fields
  • OCAJP – StringBuilder API

OCAJP Preparation Guidance

People who have already prepared for SCJP exam can easily clear OCAJP Exam. This is not a complete replacement for SCJP exam. OCAJP  Exam gives you  knowledge on data types, strings, operators, exception and Java basics.

  • OCAJP is the first level of Java Certifications. It will just test your Java programming knowledge and not necessary to have extensive work experience for this exam.
  • Buy a good book from the market. It is very important to read each and every line of the book to understand all the concepts. Don’t just think about passing the exam, try to understand the concepts and answer the questions. That only will help you when you join a company as Java programmer.
    • OCA Java SE 7 Programmer I Certification Guide (by Mala Gupta)
    • OCA/OCP Java SE 7 Programmer I & II Study Guide (by Kathy Sierra & Bert Bates)
  • Practice. Practice.Practice. – Yes. That is the only way you would learn anything that will last for the rest of your life. Practice helps you to understand the concepts in-depth and avoid any confusion on the topics.
  • Get some free mock exams in the internet and try to answer the questions.
  • Buy any of the good mock exam simulator and test your knowledge. Note that this step has to be done only when you are ready for the exam. This should be the final step before the real exam.
  • Last but not least, have confidence and faith on you, that will help you lot for the success!!

 

Recommended Books for OCAJP

ocajp 7 manning

Book Title: OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1Z0-803 Exam

Author: Mala Gupta 

Recommendation: It is one of the best books for learning OCAJP 7 concepts. Manning books are easy to understand and covers all the important topics covered in the exam. Also the mock exams available for practice would be very helpful.

Buy From FlipKart

Filed Under: Certifications Tagged With: OCAJP

  • 1
  • 2
  • 3
  • …
  • 7
  • Next Page »

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved