Java SE 8 Programmer

                         Java SE 8 Programmer I Exam

 

 

 


 

 

 

     The Java Tutorials to topics covered in the Java SE 8 Programmer I exam.

 

 

 

1.    JAVA BASICS

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

9.    WORKING WITH SELECTED CLASSES FROM THE JAVA API.  

 

 

                                    Section 1: Java Basics

 ITEMS 1:   Variables

                              

A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

 

Types of Variables

There are three types of variables in Java:

  • local variable
  • instance variable
  • static variable

  

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called instance variable. It is not declared as static.

It is called instance variable because its value is instance specific and is not shared among instances.

 

3) Static variable

A variable which is declared as static is called static variable. It cannot be local. You can create a single copy of static variable and share among all the instances of the class. Memory allocation for static variable happens only once when the class is loaded in the memory.

 

ITEM 2:Define the structure of a Java class:

Objects and Classes in Java

In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes.

An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

What is an object in Java



An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.

An object has three characteristics:

o    State: represents the data (value) of an object.

o    Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.

o    Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.

 

Object Definitions:

  • An object is a real-world entity.
  • An object is a runtime entity.
  • The object is an entity which has state and behavior.
  • The object is an instance of a class.

What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

  • Fields
  • Methods
  • Constructors
  • Blocks
  • Nested class and interface

 

 Import other Java packages to make them accessible in your code

java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

 

Java Package

1.       Java Package

2.       Example of package

3.       Accessing package

1.       By import packagename.*

2.       By import packagename.classname

3.       By fully qualified name

4.       Subpackage

5.       Sending class file to another directory

6.       -classpath switch

7.       4 ways to load the class file or jar file

8.       How to put two public class in a package

9.       Static Import

10.   Package class

java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package

The package keyword is used to create a package in java.

1.       package mypack;  

2.       public class Simple{  

3.        public static void main(String args[]){  

4.           System.out.println("Welcome to package");  

5.          }  

6.       }  

How to access package from another package?

There are three ways to access the package from outside the package.

1.       import package.*;

2.       import package.classname;

3.       fully qualified name.

Java OOPs Concepts

1.     Object-Oriented Programming

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritancedata bindingpolymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:

o    Object

o    Class

o    Inheritance

o    Polymorphism

o    Abstraction

o    Encapsulation

Apart from these concepts, there are some other terms which are used in Object-Oriented design:

o    Coupling

o    Cohesion

o    Association

o    Aggregation

o    Composition

 

Object

 

Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects.

Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like wagging the tail, barking, eating, etc.

Class

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

Inheritance

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

 

Polymorphism

If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

Abstraction

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

 

Encapsulation

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

Coupling

Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.

Cohesion

Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.

Association

Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:

o    One to One

o    One to Many

o    Many to One, and

o    Many to Many

Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

 

 

Aggregation

Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.

Composition

The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.

 

 

              SECTION 2:Working with Java Data Types

 

ITEM 1:Differentiate between object reference variables and primitive variables.

 

Primitive Data Types

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name, as you've already seen:

int gear = 1;

Doing so tells your program that a field named "gear" exists, holds numerical data, and has an initial value of "1". A variable's data type determines the values it may contain, plus the operations that may be performed on it. In addition to int, the Java programming language supports seven other primitive data types. A primitive type is predefined by the language and is named by a reserved keyword. Primitive values do not share state with other primitive values. The eight primitive data types supported by the Java programming language are:

·         byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

·         short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

·         int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigneddivideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

·         long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigneddivideUnsigned etc to support arithmetic operations for unsigned long.

·         float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

·         double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

·         boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

·         char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Simple Data Objects

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

The following chart summarizes the default values for the above data types.

Data Type

Default Value (for fields)

Byte

0

Short

0

Int

0

Long

0L

Float

0.0f

Double

0.0d

Char

'\u0000'

String (or any object)  

Null

Boolean

False

 

 

 

The Numbers Classes

When working with numbers, most of the time you use the primitive types in your code. For example:

int i = 500;
float gpa = 3.65f;
byte mask = 0x7f;

There are, however, reasons 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 in an object. Often, the wrapping is done by the compiler—if you use a primitive where an object is expected, the compiler boxes the primitive in its wrapper class for you. Similarly, if you use a number object when a primitive is expected, the compiler unboxes the object for you. For more information, see Autoboxing and Unboxing

All of the numeric wrapper classes are subclasses of the abstract class Number:

 

There are three reasons that you might use a Number object rather than a primitive:

  1. As an argument of a method that expects an object (often used when manipulating collections of numbers).
  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 use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

The following table lists the instance methods that all the subclasses of the Number class implement.

Methods Implemented by all Subclasses of Number

Method

Description

byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()

Converts the value of this Number object to the primitive data type returned.

Conversion Methods, Integer Class

Method

Description

static Integer decode(String s)

Decodes a string into an integer. Can accept string representations of decimal, octal, or hexadecimal numbers as input.

static int parseInt(String s)

Returns an integer (decimal only).

static int parseInt(String s, int radix)

Returns an integer, given a string representation of decimal, binary, octal, or hexadecimal (radix equals 10, 2, 8, or 16 respectively) numbers as input.

String toString()

Returns a String object representing the value of this Integer.

static String toString(int i)

Returns a String object representing the specified integer.

static Integer valueOf(int i)

Returns an Integer object holding the value of the specified primitive.

static Integer valueOf(String s)

Returns an Integer object holding the value of the specified string representation.

static Integer valueOf(String s, int radix)

Returns an Integer object holding the integer value of the specified string representation, parsed with the value of radix. For example, if s = "333" and radix = 8, the method returns the base-ten integer equivalent of the octal number 333.

int compareTo(Byte anotherByte)
int compareTo(Double anotherDouble)
int compareTo(Float anotherFloat)
int compareTo(Integer anotherInteger)
int compareTo(Long anotherLong)
int compareTo(Short anotherShort)

Compares this Number object to the argument.

boolean equals(Object obj)

Determines whether this number object is equal to the argument.
The methods return 
true if the argument is not null and is an object of the same type and with the same numeric value.
There are some extra requirements for 
Double and Float objects that are described in the Java API documentation.

Each Number class contains other methods that are useful for converting numbers to and from strings and for converting between number systems. The following table lists these methods in the Integer class. Methods for the other Number subclasses are similar:

 

 

 

 

ITEM 2:Know how to read or write to object fields:

 

Inheritance in Java

  1. Inheritance
  2. Types of Inheritance
  3. Why multiple inheritance is not possible in Java in case of class?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

Terms used in Inheritance

  • Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
  • Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
  • Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
  • Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.

 

 

The syntax of Java Inheritance

1.       class Subclass-name extends Superclass-name  

2.       {  

3.          //methods and fields  

4.       }  

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

 

 Java Inheritance Example



As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

1.       class Employee{  

2.        float salary=40000;  

3.       }  

4.       class Programmer extends Employee{  

5.        int bonus=10000;  

6.        public static void main(String args[]){  

7.          Programmer p=new Programmer();  

8.          System.out.println("Programmer salary is:"+p.salary);  

9.          System.out.println("Bonus of Programmer is:"+p.bonus);  

10.   }  

11.   }  

 Programmer salary is:40000.0
 Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

 

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.



 

 

When one class inherits multiple classes, it is known as multiple inheritance. For Example:



 

Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

1.       class Animal{  

2.       void eat(){System.out.println("eating...");}  

3.       }  

4.       class Dog extends Animal{  

5.       void bark(){System.out.println("barking...");}  

6.       }  

7.       class TestInheritance{  

8.       public static void main(String args[]){  

9.       Dog d=new Dog();  

10.   d.bark();  

11.   d.eat();  

12.   }}  

 

Output:

barking...
eating...

 

 

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

1.       class Animal{  

2.       void eat(){System.out.println("eating...");}  

3.       }  

4.       class Dog extends Animal{  

5.       void bark(){System.out.println("barking...");}  

6.       }  

7.       class BabyDog extends Dog{  

8.       void weep(){System.out.println("weeping...");}  

9.       }  

10.   class TestInheritance2{  

11.   public static void main(String args[]){  

12.   BabyDog d=new BabyDog();  

13.   d.weep();  

14.   d.bark();  

15.   d.eat();  

16.   }}  

Output:

weeping...
barking...
eating...
 
 Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

1.       class Animal{  

2.       void eat(){System.out.println("eating...");}  

3.       }  

4.       class Dog extends Animal{  

5.       void bark(){System.out.println("barking...");}  

6.       }  

7.       class Cat extends Animal{  

8.       void meow(){System.out.println("meowing...");}  

9.       }  

10.   class TestInheritance3{  

11.   public static void main(String args[]){  

12.   Cat c=new Cat();  

13.   c.meow();  

14.   c.eat();  

15.   //c.bark();//C.T.Error  

16.   }}  

Output:

meowing...
eating...

 

 

 

                  Section 3: Using Operators and Decision Constructs

 

 

ITEM 1:Use Java operators; use parentheses to override operator precedence.

Operators in Java

Java provides many types of operators which can be used according to the need. They are classified based on the functionality they provide. Some of the types are-

 Arithmetic Operators

Unary Operators

Assignment Operator

Relational Operators

Logical Operators

Ternary Operator

Bitwise Operators

Shift Operators

instance of operator

Precedence and Associativity

Interesting Questions

Lets take a look at them in detail.

 

 

Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types.

* : Multiplication

/ : Division

% : Modulo

+ : Addition

– : Subtraction

Unary Operators: Unary operators need only one operand. They are used to increment, decrement or negate a value.

– :Unary minus, used for negating the values.

+ :Unary plus, indicates positive value (numbers are positive without this, however). It performs an automatic conversion to int when the type of its operand is byte, char, or short. This is called unary numeric promotion.

++ :Increment operator, used for incrementing the value by 1. There are two varieties of increment operator.

Post-Increment : Value is first used for computing the result and then incremented.

Pre-Increment : Value is incremented first and then result is computed.

— : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operator.

Post-decrement : Value is first used for computing the result and then decremented.

Pre-Decrement : Value is decremented first and then result is computed.

! : Logical not operator, used for inverting a boolean value.

Assignment Operator : ‘=’ Assignment operator is used to assign a value to any variable. It has a right to left associativity, i.e value given on right hand side of operator is assigned to the variable on the left and therefore right hand side value must be declared before using it or should be a constant.

General format of assignment operator is,

 

variable = value;

In many cases assignment operator can be combined with other operators to build a shorter version of statement called Compound Statement. For example, instead of a = a+5, we can write a += 5.

+=, for adding left operand with right operand and then assigning it to variable on the left.

-=, for subtracting left operand with right operand and then assigning it to variable on the left.

*=, for multiplying left operand with right operand and then assigning it to variable on the left.

/=, for dividing left operand with right operand and then assigning it to variable on the left.

%=, for assigning modulo of left operand with right operand and then assigning it to variable on the left.

Relational Operators : These operators are used to check for relations like equality, greater than, less than. They return boolean result after the comparison and are extensively used in looping statements as well as conditional if else statements. General format is,

 

variable relation_operator value

Some of the relational operators are-

==, Equal to : returns true if left hand side is equal to right hand side.

!=, Not Equal to : returns true if left hand side is not equal to right hand side.

<, less than : returns true if left hand side is less than right hand side.

<=, less than or equal to : returns true if left hand side is less than or equal to right hand side.

>, Greater than : returns true if left hand side is greater than right hand side.

>=, Greater than or equal to: returns true if left hand side is greater than or equal to right hand side.

Logical Operators : These operators are used to perform “logical AND” and “logical OR” operation, i.e. the function similar to AND gate and OR gate in digital electronics. One thing to keep in mind is the second condition is not evaluated if the first one is false, i.e. it has a short-circuiting effect. Used extensively to test for several conditions for making a decision.

Conditional operators are-

&&, Logical AND : returns true when both conditions are true.

||, Logical OR : returns true if at least one condition is true.

Ternary operator : Ternary operator is a shorthand version of if-else statement. It has three operands and hence the name ternary. General format is-

 

condition ? if true : if false

The above statement means that if the condition evaluates to true, then execute the statements after the ‘?’ else execute the statements after the ‘:’.

 

Bitwise Operators : These operators are used to perform manipulation of individual bits of a number. They can be used with any of the integer types. They are used when performing update and query operations of Binary indexed tree.

&, Bitwise AND operator: returns bit by bit AND of input values.

|, Bitwise OR operator: returns bit by bit OR of input values.

^, Bitwise XOR operator: returns bit by bit XOR of input values.

~, Bitwise Complement Operator: This is a unary operator which returns the one’s compliment representation of the input value, i.e. with all bits inversed.

Shift Operators : These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. General format-

 

 number shift_op number_of_places_to_shift;

<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left as a result. Similar effect as of multiplying the number with some power of two.

>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit depends on the sign of initial number. Similar effect as of dividing the number with some power of two.

>>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills 0 on voids left as a result. The leftmost bit is set to 0.

instance of operator : Instance of operator is used for type checking. It can be used to test if an object is an instance of a class, a subclass or an interface.

 

ITEM 2: Create and use ifif-else, and ternary constructs:

Java if...else Statement

In this tutorial, you will learn about control flow statements using Java if and if...else statements with the help of examples.

In computer programming, we use the if statement to control the flow of the program. For example, if a certain condition is met, then run a specific block of code. Otherwise, run another code.

For example assigning grades (A, B, C) based on percentage obtained by a student.

if the percentage is above 90, assign grade A

if the percentage is above 75, assign grade B

if the percentage is above 65, assign grade C

There are three forms of if...else statements in Java.

 

if statement

if...else statement

if...else if...else statement

Nested if...else statement

 

 

 

1. Java if (if-then) Statement

The syntax of a if-then statement:

 

if (condition) {

  // statements

}

Here, condition is a boolean expression. It returns either true or false.

 

if condition evaluates to true, statements inside the body of if are executed

if condition evaluates to false, statements inside the body of if are skipped

How if statement works?

if the number is greater than 0, code inside if block is executed, otherwise code inside if block is skipped

Working of Java if statement

Example 1: Java if Statement

class IfStatement {

  public static void main(String[] args) {

 int number = 10;    // checks if number is greater than 0

    if (number > 0) {

      System.out.println("The number is positive.");

    }System.out.println("Statement outside if block");

  }

}

 

Output

 

The number is positive.

Statement outside if block

In the above example, we have created a variable named number. Notice the test condition,

number > 0

Here, the condition is checking if number is greater than 0. Since number is greater than 0, the condition evaluates true.If we change the variable to a negative integer. Let's say -5.

int number = -5;

Now, when we run the program, the output will be:

Statement outside if block

This is because the value of number is less than 0. Hence, the condition evaluates to false. And, the body of if block is skipped.

Note: To learn about condition expression, make sure to visit Java Relational Operators and Java Logical Operators.

We can also use Java Strings as the test condition.

Example 2: Java if with String

class Main {

  public static void main(String[] args) {

    // create a string variable

    String language = "Java";

 

    // if statement

    if (language == "Java") {

      System.out.println("Best Programming Language");

    }

  }

}

Output

 

Best Programming Language

In the above example, we are comparing two strings in the if block.

 

2. Java if...else (if-then-else) Statement

The if statement executes a certain section of code if the test expression is evaluated to true. However, if the test expression is evaluated to false, it does nothing.

In this case, we can use an optional else block. Statements inside the body of else block are executed if the test expression is evaluated to false. This is known as the if-...else statement in Java.

 

The syntax of the if...else statement is:

if (condition) {

  // codes in if block

}else {

  // codes in else block}

Here, the program will do one task (codes inside if block) if the condition is true and another task (codes inside else block) if the condition is false.

 

How the if...else statement works?

If the condition is true, the code inside the if block is executed, otherwise, code inside the else block is executed

Working of Java if-else statements

 

Example 3: Java if...else Statement

class Main {

  public static void main(String[] args) {

    int number = 10;

 

    // checks if number is greater than 0

    if (number > 0) {

      System.out.println("The number is positive.");

    }

   // execute this block

    // if number is not greater than 0

    else {

      System.out.println("The number is not positive.");

    } System.out.println("Statement outside if...else block");

  }

}

 

Output

 

The number is positive.

Statement outside if...else block

In the above example, we have a variable named number. Here, the test expression number > 0 checks if number is greater than 0.

 

Since the value of the number is 10, the test expression evaluates to true. Hence code inside the body of if is executed.

Now, change the value of the number to a negative integer. Let's say -5.

int number = -5;

If we run the program with the new value of number, the output will be:

 

The number is not positive.

Statement outside if...else block

Here, the value of number is -5. So the test expression evaluates to false. Hence code inside the body of else is executed.

 

3. Java if...else...if Statement

In Java, we have an if...else...if ladder, that can be used to execute one block of code among multiple other blocks.

 

if (condition1) {

  // codes

}

else if(condition2) {

  // codes

}

else if (condition3) {

  // codes

}

.

.

else {

  // codes

}

Here, if statements are executed from the top towards the bottom. When the test condition is true, codes inside the body of that if block is executed. And, program control jumps outside the if...else...if ladder.

 

If all test expressions are false, codes inside the body of else are executed.

 

How the if...else...if ladder works?

If the first test condition if true, code inside first if block is executed, if the second condition is true, block inside second if is executed, and if all conditions are false, the else block is executed

Working of if...else...if ladder

Example 4: Java if...else...if Statement

class Main {

  public static void main(String[] args) {

int number = 0;

    // checks if number is greater than 0

    if (number > 0) {      System.out.println("The number is positive.");    }

// checks if number is less than 0

    else if (number < 0) {

      System.out.println("The number is negative.");

    }

   

    // if both condition is false

    else {

      System.out.println("The number is 0.");

    }

  }

}

Output

 

The number is 0.

In the above example, we are checking whether number is positive, negative, or zero. Here, we have two condition expressions:

 

number > 0 - checks if number is greater than 0

number < 0 - checks if number is less than 0

Here, the value of number is 0. So both the conditions evaluate to false. Hence the statement inside the body of else is executed.

 

Note: Java provides a special operator called ternary operator, which is a kind of shorthand notation of if...else...if statement. To learn about the ternary operator, visit Java Ternary Operator.

 

4. Java Nested if..else Statement

In Java, it is also possible to use if..else statements inside an if...else statement. It's called the nested if...else statement.

Here's a program to find the largest of 3 numbers using the nested if...else statement.

 

 

Example 5: Nested if...else Statement

class Main {

  public static void main(String[] args) {

 

    // declaring double type variables

    Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largest;

 

    // checks if n1 is greater than or equal to n2

    if (n1 >= n2) {

 

      // if...else statement inside the if block

      // checks if n1 is greater than or equal to n3

      if (n1 >= n3) {

        largest = n1;

      }

 

      else {

        largest = n3;

      }

    } else {

// if..else statement inside else block

      // checks if n2 is greater than or equal to n3

      if (n2 >= n3) {

        largest = n2; }

else {        largest = n3;

      }

    }system.out.println("Largest Number: " + largest);

  }

}

Output:

 

Largest Number: 4.5

In the above programs, we have assigned the value of variables ourselves to make this easier.However, in real-world applications, these values may come from user input data, log files, form submission, etc.

Java switch Statement

In this tutorial, you will learn to use the switch statement in Java to control the flow of your program’s execution with the help of examples.

The switch statement allows us to execute a block of code among many alternatives.

The syntax of the switch statement in Java is:

switch (expression) {

case value1:

    // code    break;

 

  case value2:

    // code

    break;

default   // default statements

 }

How does the switch-case statement work?

 

The expression is evaluated once and compared with the values of each case.

If expression matches with value1, the code of case value1 are executed. Similarly, the code of case value2 is executed if expression matches with value2.

If there is no match, the code of the default case is executed.

Note: The working of the switch-case statement is similar to the Java if...else...if ladder. However, the syntax of the switch statement is cleaner and much easier to read and write.

 

Example: Java switch Statement

// Java Program to check the size

// using the switch...case statement

class Main {

  public static void main(String[] args) {

    int number = 44;

    String size;

    // switch statement to check size

    switch (number) {

      case 29:

       size = "Small";

        break;

        case 42;

size = "Medium";

        break;

// match the value of week

    default:

        size = "Unknown";

        break;  }

    System.out.println("Size: " + size);

  }}

Output:

Size: Large

In the above example, we have used the switch statement to find the size. Here, we have a variable number. The variable is compared with the value of each case statement.

 

Since the value matches with 44, the code of case 44 is executed.

size = "Large";

break;

Here, the size variable is assigned with the value Large.

 

Recommended Reading: Create a Simple Calculator Using the Java switch Statement

 

The break statement is used to terminate the switch-case statement. If break is not used, all the cases after the matching case are also executed. For example,

 

class Main {

  public static void main(String[] args) {

  int expression = 2;

    // switch statement to check size

    switch (expression) {

      case 1:       System.out.println("Case 1");

        // matching case

      case 2:

        System.out.println("Case 2");

      case 3:

        System.out.println("Case 3");

      default:

        System.out.println("Default case");

    }

  }

}

Output

 

Case 2

Case 3     

Default case

In the above example, expression matches with case 2. Here, we haven't used the break statement after each case.

Hence, all the cases after case 2 are also executed.

This is why the break statement is needed to terminate the switch-case statement after the matching case. To learn more, visit Java break Statement.

 

default case in Java switch-case

The switch statement also includes an optional default case. It is executed when the expression doesn't match any of the cases. For example,

 

class Main {

  public static void main(String[] args) {

   int expression = 9;

      switch(expression) {

          case 2:

        System.out.println("Small Size");

        break;

case 3:

        System.out.println("Large Size");

        break;

        // default case

      default:

        System.out.println("Unknown Size");

    }

  }

}

Output

Unknown Size

In the above example, we have created a switch-case statement. Here, the value of expression doesn't match with any of the cases.

Hence, the code inside the default case is executed.

default:

  System.out.println("Unknown Size);

 

                                 Java Arrays

In this tutorial, we will learn to work with arrays in Java. We will learn to declare, initialize, and access array elements with the help of examples.

An array is a collection of similar types of data.

For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names.

String[] array = new String[100];

Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed.

How to declare an array in Java?

In Java, here is how we can declare an array.

dataType[] arrayName;

dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects

arrayName - it is an identifier

For example,

double[] data;

Here, data is an array that can hold values of type double.

 

But, how many elements can array this hold?

Good question! To define the number of elements that an array can hold, we have to allocate memory for the array in Java. For example,

 

// declare an array

double[] data;

 

// allocate memory

data = new Double[10];

Here, the array can store 10 elements. We can also say that the size or length of the array is 10.

In Java, we can declare and allocate memory of an array in one single statement. For example,

double[] data = new double[10];

How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array

int[] age = {12, 4, 5, 2, 5};

Here, we have created an array named age and initialized it with the values inside the curly brackets.

Note that we have not provided the size of the array. In this case, the Java compiler automatically specifies the size by counting the number of elements in the array (i.e. 5).

In the Java array, each memory location is associated with a number. The number is known as an array index. We can also initialize arrays in Java, using the index number. For example,

// declare an array

int[] age = new int[5];

// initialize array

age[0] = 12;

age[1] = 4;

age[2] = 5;

..

Elements are stored in the array

Java Arrays initialization

Note:

 

Array indices always start from 0. That is, the first element of an array is at index 0.

If the size of an array is n, then the last element of the array will be at index n-1.

How to Access Elements of an Array in Java?

We can access the element of an array using the index number. Here is the syntax for accessing elements of an array,

/ access array elements

array[index]

Let's see an example of accessing array elements using index numbers.

 

Example: Access Array Elements

class Main {

 public static void main(String[] args) {

  // create an array

   int[] age = {12, 4, 5, 2, 5};

 // access each array elements

   System.out.println("Accessing Elements of Array:");

   System.out.println("First Element: " + age[0]);

   System.out.println("Second Element: " + age[1]);

   System.out.println("Third Element: " + age[2]);

   System.out.println("Fourth Element: " + age[3]);

   System.out.println("Fifth Element: " + age[4]);

 }

}

Output

 

Accessing Elements of Array:

First Element: 12

Second Element: 4

Third Element: 5

Fourth Element: 2

Fifth Element: 5

In the above example, notice that we are using the index number to access each element of the array.

We can use loops to access all the elements of the array at once.

Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,

 

Example: Using For Loop

class Main {

 public static void main(String[] args) {

     // create an array

   int[] age = {12, 4, 5};

 // loop through the array

   // using for loop

   System.out.println("Using for Loop:");

   for(int i = 0; i < age.length; i++) {

     System.out.println(age[i]);

   }

 }

 

Output

 

Using for Loop:

12

4

5

In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop,

age.length

Here, we are using the length property of the array to get the size of the array.

We can also use the for-each loop to iterate through the elements of an array. For example,

Example: Using the for-each Loop

class Main {

 public static void main(String[] args) {

  // create an array

   int[] age = {12, 4, 5};

 // loop through the array

   // using for loop

   System.out.println("Using for-each Loop:");

   for(int a : age) {

     System.out.println(a);

   }

 }

}

Output

 

Using for-each Loop:

12

4

5

Example: Compute Sum and Average of Array Elements

class Main {

 public static void main(String[] args) {

 

   int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};

   int sum = 0;

   Double average;

  

   // access all elements using for each loop

   // add each element in sum

   for (int number: numbers) {

     sum += number;

   }

 // get the total number of elements

   int arrayLength = numbers.length;

  // calculate the average

   // convert the average from int to double

   average =  ((double)sum / (double)arrayLength);

   System.out.println("Sum = " + sum);

   System.out.println("Average = " + average);

 }

}

Output:

Sum = 36

Average = 3.6

In the above example, we have created an array of named numbers. We have used the for...each loop to access each element of the array.

Inside the loop, we are calculating the sum of each element. Notice the line,

int arrayLength = number.length;

Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using:

average = ((double)sum / (double)arrayLength);

As you can see, we are converting the int value into double. This is called type casting in Java. To learn more about typecasting, visit Java Type Casting.

 

Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,

 

double[][] matrix = {{1.2, 4.3, 4.0},

      {4.1, -1.1}

};

Here, we have created a multidimensional array named matrix. It is a 2-dimensional array. To learn more, visit the Java multidimensional array.

 

Java Multidimensional Arrays

In this tutorial, we will learn about the Java multidimensional array using 2-dimensional arrays and 3-dimensional arrays with the help of examples.

Before we learn about the multidimensional array, make sure you know about Java array.

A multidimensional array is an array of arrays. Each element of a multidimensional array is an array itself. For example,

int[][] a = new int[3][4];

Here, we have created a multidimensional array named a. It is a 2-dimensional array, that can hold a maximum of 12 elements,


2-dimensional Array

Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts with 0 and not 1.

Let's take another example of the multidimensional array. This time we will be creating a 3-dimensional array. For example,

String[][][] data = new String[3][4][2];

Here, data is a 3d array that can hold a maximum of 24 (3*4*2) elements of type String.

How to initialize a 2d array in Java?

Here is how we can initialize a 2-dimensional array in Java.

int[][] a = {
      {1, 2, 3}, 
      {4, 5, 6, 9}, 
      {7}, 
};

As we can see, each element of the multidimensional array is an array itself. And also, unlike C/C++, each row of the multidimensional array in Java can be of different lengths.


Initialization of 2-dimensional Array

Example: 2-dimensional Array

class MultidimensionalArray {
    public static void main(String[] args) {
 
        // create a 2d array
        int[][] a = {
            {1, 2, 3}, 
            {4, 5, 6, 9}, 
            {7}, 
        };
      
        // calculate the length of each row
        System.out.println("Length of row 1: " + a[0].length);
        System.out.println("Length of row 2: " + a[1].length);
        System.out.println("Length of row 3: " + a[2].length);
    }
}

Output:

Length of row 1: 3
Length of row 2: 4
Length of row 3: 1

In the above example, we are creating a multidimensional array named a. Since each component of a multidimensional array is also an array (a[0]a[1] and a[2] are also arrays).

Here, we are using the length attribute to calculate the length of each row.

Example: Print all elements of 2d array Using Loop

class MultidimensionalArray {
    public static void main(String[] args) {
 
        int[][] a = {
            {1, -2, 3}, 
            {-4, -5, 6, 9}, 
            {7}, 
        };
      
        for (int i = 0; i < a.length; ++i) {
            for(int j = 0; j < a[i].length; ++j) {
                System.out.println(a[i][j]);
            }
        }
    }
}

Output:

1
-2
3
-4
-5
6
9
7

We can also use the for...each loop to access elements of the multidimensional array. For example,

class MultidimensionalArray {
    public static void main(String[] args) {
 
        // create a 2d array
        int[][] a = {
            {1, -2, 3}, 
            {-4, -5, 6, 9}, 
            {7}, 
        };
      
        // first for...each loop access the individual array
        // inside the 2d array
        for (int[] innerArray: a) {
            // second for...each loop access each element inside the row
            for(int data: innerArray) {
                System.out.println(data);
            }
        }
    }
}

Output:

1
-2
3
-4
-5
6
9
7

In the above example, we are have created a 2d array named a. We then used for loop and for...each loop to access each element of the array.

How to initialize a 3d array in Java?

Let's see how we can use a 3d array in Java. We can initialize a 3d array similar to the 2d array. For example,

// test is a 3d array
int[][][] test = {
        {
          {1, -2, 3}, 
          {2, 3, 4}
        }, 
        { 
          {-4, -5, 6, 9}, 
          {1}, 
          {2, 3}
        } 
};

Basically, a 3d array is an array of 2d arrays. The rows of a 3d array can also vary in length just like in a 2d array.

Example: 3-dimensional Array

class ThreeArray {
    public static void main(String[] args) {
 
        // create a 3d array
        int[][][] test = {
            {
              {1, -2, 3}, 
              {2, 3, 4}
            }, 
            { 
              {-4, -5, 6, 9}, 
              {1}, 
              {2, 3}
            } 
        };
 
        // for..each loop to iterate through elements of 3d array
        for (int[][] array2D: test) {
            for (int[] array1D: array2D) {
                for(int item: array1D) {
                    System.out.println(item);
                }
            }
        }
    }
}

Output:

1
-2
3
2
3
4
-4
-5
6
9
1
2
3

 Using Loop Constructs:

Java while and do...while Loop

In this tutorial, we will learn how to use while and do while loop in Java with the help of examples.

In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then you can use a loop. It's just a simple example; you can achieve much more with loops.

In the previous tutorial, you learned about Java for loop. Here, you are going to learn about while and do...while loops.

 

Java while loop

Java while loop is used to run a specific code until a certain condition is met. The syntax of the while loop is:

while (testExpression) {
    // body of loop
}

Here,

1.       while loop evaluates the textExpression inside the parenthesis ().

2.       If the textExpression evaluates to true, the code inside the while loop is executed.

3.       The textExpression is evaluated again.

4.       This process continues until the textExpression is false.

5.       When the textExpression evaluates to false, the loop stops.

To learn more about the conditions, visit Java relational and logical operators.

Flowchart of while loop


Flowchart of Java while loop


Example 1: Display Numbers from 1 to 5

// Program to display numbers from 1 to 5
 
class Main {
  public static void main(String[] args) {
 
    // declare variables
    int i = 1, n = 5;
 
    // while loop from 1 to 5
    while(i <= n) {
      System.out.println(i);
      i++;
    }
  }
}

Output

1
2
3
4
5

Here is how this program works.

Iteration

Variable

Condition: i <= n

Action

1st

i = 1
n = 5

True

1 is printed.
i is increased to 2.

2nd

i = 2
n = 5

True

2 is printed.
i is increased to 3.

3rd

i = 3
n = 5

True

3 is printed.
i is increased to 4.

4th

i = 4
n = 5

True

4 is printed.
i is increased to 5.

5th

i = 5
n = 5

True

5 is printed.
i is increased to 6.

6th

i = 6
n = 5

False

The loop is terminated

Example 2: Sum of Positive Numbers Only

// Java program to find the sum of positive numbers
import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
      
    int sum = 0;
 
    // create an object of Scanner class
    Scanner input = new Scanner(System.in);
 
    // take integer input from the user
    System.out.println("Enter a number");
    int number = input.nextInt();
                  
    // while loop continues 
    // until entered number is positive
    while (number >= 0) {
      // add only positive numbers
      sum += number;
 
      System.out.println("Enter a number");
      number = input.nextInt();
    }
                  
    System.out.println("Sum = " + sum);
    input.close();
  }
}

Output

Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39

In the above program, we have used the Scanner class to take input from the user. Here, nextInt() takes integer input from the user.

The while loop continues until the user enters a negative number. During each iteration, the number entered by the user is added to the sum variable.

When the user enters a negative number, the loop terminates. Finally, the total sum is displayed.

Java do...while loop

The do...while loop is similar to while loop. However, the body of do...while loop is executed once before the test expression is checked. For example,

do {
    // body of loop
} while(textExpression)

Here,

1.       The body of the loop is executed at first. Then the textExpression is evaluated.

2.       If the textExpression evaluates to true, the body of the loop inside the do statement is executed again.

3.       The textExpression is evaluated once again.

4.       If the textExpression evaluates to true, the body of the loop inside the do statement is executed again.

5.       This process continues until the textExpression evaluates to false. Then the loop stops.

 

 Flowchart of do...while loop



Flowchart of Java do while loop

 

Let's see the working of do...while loop.

Example 3: Display Numbers from 1 to 5

// Java Program to display numbers from 1 to 5
 
import java.util.Scanner;
 
// Program to find the sum of natural numbers from 1 to 100.
 
class Main {
  public static void main(String[] args) {
 
    int i = 1, n = 5;
 
    // do...while loop from 1 to 5
    do {
      System.out.println(i);
      i++;
    } while(i <= n);
  }
}

Output

1
2
3
4
5

Here is how this program works.

Iteration

Variable

Condition: i <= n

Action

 

i = 1
n = 5

not checked

1 is printed.
i is increased to 2.

1st

i = 2
n = 5

true

2 is printed.
i is increased to 3.

2nd

i = 3
n = 5

true

3 is printed.
i is increased to 4.

3rd

i = 4
n = 5

true

4 is printed.
i is increased to 5.

4th

i = 5
n = 5

true

6 is printed.
i is increased to 6.

5th

i = 6
n = 5

false

The loop is terminated


Example 4: Sum of Positive Numbers

// Java program to find the sum of positive numbers
import java.util.Scanner;
 
class Main {
  public static void main(String[] args) {
      
    int sum = 0;
    int number = 0;
 
    // create an object of Scanner class
    Scanner input = new Scanner(System.in);
                  
    // do...while loop continues 
    // until entered number is positive
    do {
      // add only positive numbers
      sum += number;
      System.out.println("Enter a number");
      number = input.nextInt();
    } while(number >= 0); 
                  
    System.out.println("Sum = " + sum);
    input.close();
  }
}

Output 1

Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39

Here, the user enters a positive number, that number is added to the sum variable. And this process continues until the number is negative. When the number is negative, the loop terminates and displays the sum without adding the negative number.

Output 2

Enter a number
-8
Sum is 0

Here, the user enters a negative number. The test condition will be false but the code inside of the loop executes once.

Infinite while loop

If the condition of a loop is always true, the loop runs for infinite times (until the memory is full). For example,

// infinite while loop
while(true){
    // body of loop
}

Here is an example of an infinite do...while loop.

// infinite do...while loop
int count = 1;
do {
   // body of loop
} while(count == 1)

In the above programs, the textExpression is always true. Hence, the loop body will run for infinite times.

for and while loops

The for loop is used when the number of iterations is known. For example,

for (let i = 1; i <=5; ++i) {
   // body of loop
}

And while and do...while loops are generally used when the number of iterations is unknown. For example,

while (condition) {
    // body of loop
}

Java for Loop

In this tutorial, we will learn how to use for loop in Java with the help of examples and we will also learn about the working of Loop in computer programming.

In computer programming, loops are used to repeat a block of code. For example, if you want to show a message 100 times, then rather than typing the same code 100 times, you can use a loop.

In Java, there are three types of loops.

·         for loop

·         while loop

·         do...while loop

Java for Loop

Java for loop is used to run a block of code for a certain number of times. The syntax of for loop is:

for (initialExpression; testExpression; updateExpression) {
    // body of the loop
}

Here,

1.       The initialExpression initializes and/or declares variables and executes only once.

2.       The condition is evaluated. If the condition is true, the body of the for loop is executed.

3.       The updateExpression updates the value of initialExpression.

4.       The condition is evaluated again. The process continues until the condition is false.

To learn more about the conditions, visit Java relational and logical operators.

 

Flowchart of Java for loop



 

Example 1: Display a Text Five Times

// Program to print a text 5 times
 
class Main {
  public static void main(String[] args) {
 
    int n = 5;
    // for loop  
    for (int i = 1; i <= n; ++i) {
      System.out.println("Java is fun");
    }
  }
}

Output

Java is fun
Java is fun
Java is fun
Java is fun
Java is fun

Here is how this program works.

Iteration

Variable

Condition: i <= n

Action

1st

i = 1
n = 5

true

Java is fun is printed.
i is increased to 2.

2nd

i = 2
n = 5

true

Java is fun is printed.
i is increased to 3.

3rd

i = 3
n = 5

true

Java is fun is printed.
i is increased to 4.

4th

i = 4
n = 5

true

Java is fun is printed.
i is increased to 5.

5th

i = 5
n = 5

true

Java is fun is printed.
i is increased to 6.

6th

i = 6
n = 5

false

The loop is terminated.


Example 2: Display numbers from 1 to 5

// Program to print numbers from 1 to 5
 
class Main {
  public static void main(String[] args) {
  
    int n = 5;
    // for loop  
    for (int i = 1; i <= n; ++i) {
      System.out.println(i);
    }
  }
}

Output

1
2
3
4
5

Here is how the program works.

Iteration

Variable

Condition: i <= n

Action

1st

i = 1
n = 5

true

1 is printed.
i is increased to 2.

2nd

i = 2
n = 5

true

2 is printed.
i is increased to 3.

3rd

i = 3
n = 5

true

3 is printed.
i is increased to 4.

4th

i = 4
n = 5

true

4 is printed.
i is increased to 5.

5th

i = 5
n = 5

true

5 is printed.
i is increased to 6.

6th

i = 6
n = 5

false

The loop is terminated.


Example 3: Display Sum of n Natural Numbers

// Program to find the sum of natural numbers from 1 to 1000.
 
class Main {
  public static void main(String[] args) {
      
    int sum = 0;
    int n = 1000;
 
    // for loop
    for (int i = 1; i <= n; ++i) {
      // body inside for loop
      sum += i;     // sum = sum + i
    }
       
    System.out.println("Sum = " + sum);
  }
}

Output:

Sum = 500500

Here, the value of sum is 0 initially. Then, the for loop is iterated from i = 1 to 1000. In each iteration, iis added to sum and its value is increased by 1.

When i becomes 1001, the test condition is false and sum will be equal to 0 + 1 + 2 + .... + 1000.

 

The above program to add the sum of natural numbers can also be written as

// Program to find the sum of natural numbers from 1 to 1000.
 
class Main {
  public static void main(String[] args) {
      
    int sum = 0;
    int n = 1000;
 
    // for loop
    for (int i = n; i >= 1; --i) {
      // body inside for loop
      sum += i;     // sum = sum + i
    }
       
    System.out.println("Sum = " + sum);
  }
}

The output of this program is the same as the Example 3.

Java for-each Loop

The Java for loop has an alternative syntax that makes it easy to iterate through arrays and collections. For example,

// print array elements 
 
class Main {
  public static void main(String[] args) {
      
    // create an array
    int[] numbers = {3, 7, 5, -5};
    
    // iterating through the array 
    for (int number: numbers) {
       System.out.println(number);
    }
  }
}

Output

3
7
5
-5

Here, we have used the for-each loop to print each element of the numbers array one by one.

In the first iteration of the loop, number will be 3, number will be 7 in second iteration and so on.

To learn more, visit Java for-each Loop.

Java Infinite for Loop

If we set the test expression in such a way that it never evaluates to false, the for loop will run forever. This is called infinite for loop. For example,

// Infinite for Loop
 
class Infinite {
    public static void main(String[] args) {
      
        int sum = 0;
 
        for (int i = 1; i <= 10; --i) {
            System.out.println("Hello");
        }
    }
}

Here, the test expression ,i <= 10, is never false and Hello is printed repeatedly until the memory runs out.

Java for-each Loop

In this tutorial, we will learn about the Java for-each loop and its difference with for loop with the help of examples.

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.

for-each Loop Sytnax

The syntax of the Java for-each loop is:

for(dataType item : array) {
    ...
}

Here,

·         array - an array or a collection

·         item - each item of array/collection is assigned to this variable

·         dataType - the data type of the array/collection

Example 1: Print Array Elements

// print array elements 
 
class Main {
  public static void main(String[] args) {
      
    // create an array
    int[] numbers = {3, 9, 5, -5};
    
    // for each loop 
    for (int number: numbers) {
      System.out.println(number);
    }
  }
}

Output

3
9
5
-5

Here, we have used the for-each loop to print each element of the numbers array one by one.

·         In the first iteration, item will be 3.

·         In the second iteration, item will be 9.

·         In the third iteration, item will be 5.

·         In the fourth iteration, item will be -5.

Example 2: Sum of Array Elements

// Calculate the sum of all elements of an array
 
class Main {
 public static void main(String[] args) {
  
   // an array of numbers
   int[] numbers = {3, 4, 5, -5, 0, 12};
   int sum = 0;
 
   // iterating through each element of the array 
   for (int number: numbers) {
     sum += number;
   }
  
   System.out.println("Sum = " + sum);
 }
}

 

 

Output:

Sum = 19

In the above program, the execution of the for each loop looks as:

Iteration

Variables

1

number = 3
sum = 0 + 3 = 3

2

number = 4
sum = 3 + 4 = 7

3

number = 5
sum = 7 + 5 = 12

4

number = -5
sum = 12 + (-5) = 7

5

number = 0
sum = 7 + 0 = 7

6

number = 12
sum = 7 + 12 = 19

As we can see, we have added each element of the numbers array to the sum variable in each iteration of the loop.

for loop Vs for-each loop

Let's see how a for-each loop is different from a regular Java for loop.

1. Using for loop

class Main {
 public static void main(String[] args) {
    
   char[] vowels = {'a', 'e', 'i', 'o', 'u'};
 
   // iterating through an array using a for loop
   for (int i = 0; i < vowels.length; ++ i) {
     System.out.println(vowels[i]);
   }
 }
}

Output:

a
e
i
o
u

2. Using for-each Loop

class Main {
 public static void main(String[] args) {
 
   char[] vowels = {'a', 'e', 'i', 'o', 'u'};
  
   // iterating through an array using the for-each loop
   for (char item: vowels) {
     System.out.println(item);
   }
 }
}

Output:

a
e
i
o
u

Here, the output of both programs is the same. However, the for-each loop is easier to write and understand.

This is why the for-each loop is preferred over the for loop when working with arrays and collections.

Java break Statement

In this tutorial, you will learn about the break statement, labeled break statement in Java with the help of examples.

While working with loops, it is sometimes desirable to skip some statements inside the loop or terminate the loop immediately without checking the test expression.

In such cases, break and continue statements are used. You will learn about the Java continue statement in the next tutorial.

The break statement in Java terminates the loop immediately, and the control of the program moves to the next statement following the loop.

It is almost always used with decision-making statements (Java if...else Statement).

Here is the syntax of the break statement in Java:

break;

 

How break statement works?


Working of Java break Statement



Example 1: Java break statement

class Test {
    public static void main(String[] args) {
      
        // for loop
        for (int i = 1; i <= 10; ++i) {
 
            // if the value of i is 5 the loop terminates  
            if (i == 5) {
                break;
            }      
            System.out.println(i);
        }   
    }
}

Output:

1
2
3
4

In the above program, we are using the for loop to print the value of i in each iteration. To know how for loop works, visit the Java for loop. Here, notice the statement,

if (i == 5) {
    break;
}

This means when the value of i is equal to 5, the loop terminates. Hence we get the output with values less than 5 only.

Example 2: Java break statement

The program below calculates the sum of numbers entered by the user until user enters a negative number.To take input from the user, we have used the Scanner object. To learn more about Scanner, visit Java Scanner.

import java.util.Scanner;
 
class UserInputSum {
    public static void main(String[] args) {
      
        Double number, sum = 0.0;
 
        // create an object of Scanner
        Scanner input = new Scanner(System.in);
      
        while (true) {
            System.out.print("Enter a number: ");
 
            // takes double input from user
            number = input.nextDouble();
         
            // if number is negative the loop terminates
            if (number < 0.0) {
                break;
            }
         
           sum += number;
        }
        System.out.println("Sum = " + sum);
    }
}

Output:

Enter a number: 3.2
Enter a number: 5
Enter a number: 2.3
Enter a number: 0
Enter a number: -4.5
Sum = 10.5

In the above program, the test expression of the while loop is always true. Here, notice the line,

if (number < 0.0) {
    break;
}

This means when the user input negative numbers, the while loop is terminated.

Java break and Nested Loop

In the case of nested loops, the break statement terminates the innermost loop.



Working of break Statement with Nested Loops

Here, the break statement terminates the innermost while loop, and control jumps to the outer loop.

Labeled break Statement

Till now, we have used the unlabeled break statement. It terminates the innermost loop and switch statement. However, there is another form of break statement in Java known as the labeled break.

We can use the labeled break statement to terminate the outermost loop as well.           


Working of the labeled break statement in Java

As you can see in the above image, we have used the label identifier to specify the outer loop. Now, notice how the break statement is used (break label;).

Here, the break statement is terminating the labeled statement (i.e. outer loop). Then, the control of the program jumps to the statement after the labeled statement.

Here's another example:

while (testExpression) {
   // codes
   second:
   while (testExpression) {
      // codes
      while(testExpression) {
         // codes
         break second;
      }
   }
   // control jumps here
}

In the above example, when the statement break second; is executed, the while loop labeled as second is terminated. And, the control of the program moves to the statement after the second while loop.

Example 3: labeled break Statement

class LabeledBreak {
    public static void main(String[] args) {
   
        // the for loop is labeled as first   
        first:
        for( int i = 1; i < 5; i++) {
 
            // the for loop is labeled as second
            second:
            for(int j = 1; j < 3; j ++ ) {
                System.out.println("i = " + i + "; j = " +j);
             
                // the break statement breaks the first for loop
                if ( i == 2)
                    break first;
            }
        }
    }
}

Output:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1

In the above example, the labeled break statement is used to terminate the loop labeled as first. That is,

first:
for(int i = 1; i < 5; i++) {...}

Here, if we change the statement break first; to break second; the program will behave differently. In this case, for loop labeled as second will be terminated. For example,

class LabeledBreak {
    public static void main(String[] args) {
      
        // the for loop is labeled as first
        first:
        for( int i = 1; i < 5; i++) {
 
            // the for loop is labeled as second
            second:
            for(int j = 1; j < 3; j ++ ) {
 
                System.out.println("i = " + i + "; j = " +j);
       
                // the break statement terminates the loop labeled as second   
                if ( i == 2)
                    break second;
            }
        }
    }
}

Output:

i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
i = 3; j = 1
i = 3; j = 2
i = 4; j = 1
i = 4; j = 2

 

 

 

 

Section 7: Working with Inheritance

Item 1: Describe inheritance and its benefits.

Inheritance

In the preceding lessons, you have seen inheritance mentioned several times. In the Java language, classes can be derived from other classes, thereby inheriting fields and methods from those classes.


Definitions: A class that is derived from another class is called a subclass (also a derived class, extended class, or child class). The class from which the subclass is derived is called a superclass (also a base class or a parent class).

Excepting
Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

Classes can be derived from classes that are derived from classes that are derived from classes, and so on, and ultimately derived from the topmost class,
Object. Such a class is said to be descended from all the classes in the inheritance chain stretching back to Object.

Item 2: Develop code that makes use of polymorphism; develop code that overrides methods; differentiate between the type of a reference and the type of an object.

Polymorphism

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

Polymorphism can be demonstrated with a minor modification to the Bicycle class. For example, a printDescription method could be added to the class that displays all the data currently stored in an instance.

public void printDescription(){
    System.out.println("\nBike is " + "in gear " + this.gear
        + " with a cadence of " + this.cadence +
        " and travelling at a speed of " + this.speed + ". ");
}

To demonstrate polymorphic features in the Java language, extend the Bicycle class with a MountainBike and a RoadBike class. For MountainBike, add a field for suspension, which is a String value that indicates if the bike has a front shock absorber

Item 3: Determine when casting is necessary.

Item 4: Use super and this to access objects and constructors.

Using the Keyword super

Accessing Superclass Members

If your method overrides one of its superclass's methods, you can invoke the overridden method through the use of the keyword super. You can also use super to refer to a hidden field (although hiding fields is discouraged). Consider this class, Superclass:

Using the this Keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.

 

 

 

 

                  Section 8: Handling Exceptions

 

Item 1: Differentiate among checked exceptions, RuntimeException, and Error.

 

The Catch or Specify Requirement

Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:

Code that fails to honor the Catch or Specify Requirement will not compile.

Not all exceptions are subject to the Catch or Specify Requirement. To understand why, we need to look at the three basic categories of exceptions, only one of which is subject to the Requirement.

The Three Kinds of Exceptions

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from. For example, suppose an application prompts a user for an input file name, then opens the file by passing the name to the constructor for java.io.FileReader. Normally, the user provides the name of an existing, readable file, so the construction of the FileReader object succeeds, and the execution of the application proceeds normally. But sometimes the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFoundException. A well-written program will catch this exception and notify the user of the mistake, possibly prompting for a corrected file name.

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

The second kind of exception is the error. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from. For example, suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. An application might choose to catch this exception, in order to notify the user of the problem — but it also might make sense for the program to print a stack trace and exit.

Errors are not subject to the Catch or Specify Requirement. Errors are those exceptions indicated by Error and its subclasses.

The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API. For example, consider the application described previously that passes a file name to the constructor for FileReader. If a logic error causes a null to be passed to the constructor, the constructor will throw NullPointerException. The application can catch this exception, but it probably makes more sense to eliminate the bug that caused the exception to occur.

Runtime exceptions are not subject to the Catch or Specify Requirement. Runtime exceptions are those indicated by RuntimeException and its subclasses.

Errors and runtime exceptions are collectively known as unchecked exceptions.

Item 2: Create a try-catch block and determine how exceptions alter normal program flow.

 

Catching and Handling Exceptions

This section describes how to use the three exception handler components — the try, catch, and finally blocks — to write an exception handler. Then, the try-with-resources statement, introduced in Java SE 7, is explained. The try-with-resources statement is particularly suited to situations that use Closeable resources, such as streams.

The last part of this section walks through an example and analyzes what occurs during various scenarios.

The following example defines and implements a class named ListOfNumbers. When constructed, ListOfNumbers creates an ArrayList that contains 10 Integer elements with sequential values 0 through 9. The ListOfNumbers class also defines a method named writeList, which writes the list of numbers into a text file called OutFile.txt. This example uses output classes defined in java.io, which are covered in Basic I/O.

// Note: This class will not compile yet.
import java.io.*;
import java.util.List;
import java.util.ArrayList;
 
public class ListOfNumbers {
 
    private List<Integer> list;
    private static final int SIZE = 10;
 
    public ListOfNumbers () {
        list = new ArrayList<Integer>(SIZE);
        for (int i = 0; i < SIZE; i++) {
            list.add(new Integer(i));
        }
    }
 
    public void writeList() {
                    // The FileWriter constructor throws IOException, which must be caught.
        PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
 
        for (int i = 0; i < SIZE; i++) {
            // The get(int) method throws IndexOutOfBoundsException, which must be caught.
            out.println("Value at: " + i + " = " + list.get(i));
        }
        out.close();
    }
}

The first line in boldface is a call to a constructor. The constructor initializes an output stream on a file. If the file cannot be opened, the constructor throws an IOException. The second boldface line is a call to the ArrayList class's get method, which throws an IndexOutOfBoundsException if the value of its argument is too small (less than 0) or too large (more than the number of elements currently contained by the ArrayList).

If you try to compile the ListOfNumbers class, the compiler prints an error message about the exception thrown by the FileWriter constructor. However, it does not display an error message about the exception thrown by get. The reason is that the exception thrown by the constructor, IOException, is a checked exception, and the one thrown by the get method, IndexOutOfBoundsException, is an unchecked exception.

The try Block

The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:

try {
    code
}
catch and finally blocks . . .

The segment in the example labeled code contains one or more legal lines of code that could throw an exception. (The catch and finally blocks are explained in the next two subsections.)

To construct an exception handler for the writeList method from the ListOfNumbers class, enclose the exception-throwing statements of the writeList method within a try block. There is more than one way to do this. You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each. Or, you can put all the writeList code within a single try block and associate multiple handlers with it. The following listing uses one try block for the entire method because the code in question is very short.

The catch Blocks

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.

try {
 
} catch (ExceptionType name) {
 
} catch (ExceptionType name) {
 
}

Each catch block is an exception handler that handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.

The following are two exception handlers for the writeList method:

try {
 
} catch (IndexOutOfBoundsException e) {
    System.err.println("IndexOutOfBoundsException: " + e.getMessage());
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

Exception handlers can do more than just print error messages or halt the program. They can do error recovery, prompt the user to make a decision, or propagate the error up to a higher-level handler using chained exceptions, as described in the Chained Exceptions section.

Catching More Than One Type of Exception with One Exception Handler

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

In the catch clause, specify the types of exceptions that block can handle, and separate each exception type with a vertical bar (|):

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Note: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.

Item 3: Describe the advantages of exception handling .

The term exception is shorthand for the phrase "exceptional event."


Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.


When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure).

The call stack.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the next figure, the runtime system (and, consequently, the program) terminates.

 Item 4: Create and invoke a method that throws an exception.

      Catching Exceptions

With file I/O, unexpected conditions are a fact of life: a file exists (or doesn't exist) when expected, the program doesn't have access to the file system, the default file system implementation does not support a particular function, and so on. Numerous errors can be encountered.

All methods that access the file system can throw an IOException. It is best practice to catch these exceptions by embedding these methods into a try-with-resources statement, introduced in the Java SE 7 release. The try-with-resources statement has the advantage that the compiler automatically generates the code to close the resource(s) when no longer required. The following code shows how this might look:

Charset charset = Charset.forName("US-ASCII");
String s = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, charset)) {
    writer.write(s, 0, s.length());
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
}

For more information, see The try-with-resources Statement.

Alternatively, you can embed the file I/O methods in a try block and then catch any exceptions in a catch block. If your code has opened any streams or channels, you should close them in a finally block. The previous example would look something like the following using the try-catch-finally approach:

Charset charset = Charset.forName("US-ASCII");
String s = ...;
BufferedWriter writer = null;
try {
    writer = Files.newBufferedWriter(file, charset);
    writer.write(s, 0, s.length());
} catch (IOException x) {
    System.err.format("IOException: %s%n", x);
} finally {
    if (writer != null) writer.close();
}

 

 

 

 

 

 

 

 

Working with Selected classes from the Java API

Item 1: Manipulate data using the StringBuilder class and its methods.

 

The StringBuilder Class

  StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

 

Length and Capacity

The StringBuilder class, like the String class, has a length() method that returns the length of the character sequence in the builder.

Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated. The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.

 

For example, the following code

// creates empty builder, capacity 16

StringBuilder sb = new StringBuilder();

// adds 9 character string at beginning

sb.append("Greetings");

 

 

 

StringBuilder Constructors

Constructor

Description

StringBuilder()

Creates an empty string builder with a capacity of 16 (16 empty elements).

StringBuilder(CharSequence cs)

Constructs a string builder containing the same characters as the specified CharSequence, plus an extra 16 empty elements trailing the CharSequence.

StringBuilder(int initCapacity)

Creates an empty string builder with the specified initial capacity.

StringBuilder(String s)

Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.

 

 

StringBuilder Operations

The principal operations on a StringBuilder that are not available in String are the append() and insert() methods, which are overloaded so as to accept data of any type. Each converts its argument to a string and then appends or inserts the characters of that string to the character sequence in the string builder. The append method always adds these characters at the end of the existing character sequence, while the insert method adds the characters at a specified point.

Here are a number of the methods of the StringBuilder class.

Various StringBuilder Methods

Method

Description

StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)

Appends the argument to this string builder. The data is converted to a string before the append operation takes place.

StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)

The first method deletes the subsequence from start to end-1 (inclusive) in the StringBuilder's char sequence. The second method deletes the character located at index.

StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)

Inserts the second argument into the string builder. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place.

StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)

Replaces the specified character(s) in this string builder.

StringBuilder reverse()

Reverses the sequence of characters in this string builder.

String toString()

Returns a string that contains the character sequence in the builder.

 

public class StringDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";
        int len = palindrome.length();
        char[] tempCharArray = new char[len];
        char[] charArray = new char[len];
        
        // put original string in an 
        // array of chars
        for (int i = 0; i < len; i++) {
            tempCharArray[i] = 
                palindrome.charAt(i);
        } 
        
        // reverse array of chars
        for (int j = 0; j < len; j++) {
            charArray[j] =
                tempCharArray[len - 1 - j];
        }
        
        String reversePalindrome =
            new String(charArray);
        System.out.println(reversePalindrome);
    }
}

 

 

Item 2: Create and manipulate strings.

 

 

Strings

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

 


Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

System.out.printf("The value of the float " +

                  "variable is %f, while " +

                  "the value of the " +

                  "integer variable is %d, " +

                  "and the string is %s",

                  floatVar, intVar, stringVar);

you can write

String fs;

fs = String.format("The value of the float " +

                   "variable is %f, while " +

                   "the value of the " +

                   "integer variable is %d, " +

                   " and the string is %s",

                   floatVar, intVar, stringVar);

System.out.println(fs);

 

 

 

 

Converting Between Numbers and Strings

Converting Strings to Numbers

Frequently, a program ends up with numeric data in a string object—a value entered by the user, for example.

The Number subclasses that wrap primitive numeric types ( Byte, Integer, Double, Float, Long, and Short) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:

 
public class ValueOfDemo {
    public static void main(String[] args) {
 
        // this program requires two 
        // arguments on the command line 
        if (args.length == 2) {
            // convert strings to numbers
            float a = (Float.valueOf(args[0])).floatValue(); 
            float b = (Float.valueOf(args[1])).floatValue();
 
            // do some arithmetic
            System.out.println("a + b = " +
                               (a + b));
            System.out.println("a - b = " +
                               (a - b));
            System.out.println("a * b = " +
                               (a * b));
            System.out.println("a / b = " +
                               (a / b));
            System.out.println("a % b = " +
                               (a % b));
        } else {
            System.out.println("This program " +
                "requires two command-line arguments.");
        }
    }
}

The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:

a + b = 91.7
a - b = -82.7
a * b = 392.4
a / b = 0.0516055
a % b = 4.5

Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat()) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:

float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);

Converting Numbers to Strings

Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:

int i;
// Concatenate "i" with an empty string; conversion is handled for you.
String s1 = "" + i;

or

// The valueOf class method.
String s2 = String.valueOf(i);

Each of the Number subclasses includes a class method, toString(), that will convert its primitive type to a string. For example:

int i;
double d;
String s3 = Integer.toString(i); 
String s4 = Double.toString(d); 

The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:

 
public class ToStringDemo {
    
    public static void main(String[] args) {
        double d = 858.48;
        String s = Double.toString(d);
        
        int dot = s.indexOf('.');
        
        System.out.println(dot + " digits " +
            "before decimal point.");
        System.out.println( (s.length() - dot - 1) +
            " digits after decimal point.");
    }
}

The output of this program is:

3 digits before decimal point.
2 digits after decimal point.
 
 
Item 3: Create and manipulate calendar data using classes from java.time.LocalDateTime, java.time.LocalDate, java.time.LocalTime, java.time.format.DateTimeFormatter, java.time.Period.

 

Date and Time Classes

LocalTime

The LocalTime class is similar to the other classes whose names are prefixed with Local, but deals in time only. This class is useful for representing human-based time of day, such as movie times, or the opening and closing times of the local library. It could also be used to create a digital clock, as shown in the following example:

LocalTime thisSec;
 
for (;;) {
    thisSec = LocalTime.now();
 
    // implementation of display code is left to the reader
    display(thisSec.getHour(), thisSec.getMinute(), thisSec.getSecond());
}

Date Classes

The Date-Time API provides four classes that deal exclusively with date information, without respect to time or time zone. The use of these classes are suggested by the class names: LocalDate, YearMonth, MonthDay, and Year.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

Comments

Post a Comment