Java – if-else Statement ”; Previous Next Java if-else Statement In Java, the if else statement is used to execute two code blocks based on the given condition. A Java if statement executes when the Boolean expression for the if statement is true. An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. Syntax of if-else Statement in Java Following is the syntax of an if…else statement − if(Boolean_expression) { // Executes when the Boolean expression is true }else { // Executes when the Boolean expression is false } If the boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed. Flow Diagram of if-else Statement in Java Example: Java if else statement In this example, we”re showing the usage of if else statement. We”ve created a variable x and initialized it to 30. Then in the if statement, we”re checking x with 20. As if statement is false, the statement within the else block is executed. public class Test { public static void main(String args[]) { int x = 30; if( x < 20 ) { System.out.print(“This is if statement”); }else { System.out.print(“This is else statement”); } } } Output This is else statement Java if-else-if Statement The if…else if…else statement is used for executing multiple code blocks based on the given conditions (Boolean expressions). An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using a single if…else if statement. Points to Remember When using if-else if- else statements there are a few points to keep in mind. An if can have zero or one else”s and it must come after any else if”s. An if can have zero to many else if”s and they must come before the else. Once an else if succeeds, none of the remaining else if”s or else”s will be tested. Syntax of if-else-if statement Following is the syntax of an if…else if…else statement − if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true }else if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true }else if(Boolean_expression 3) { // Executes when the Boolean expression 3 is true }else { // Executes when the none of the above condition is true. } Example 1: Java if … else if … else statement In this example, we”re showing the usage of if…else if…else statement. We”ve created a variable x and initialized it to 30. Then in the if statement, we”re checking x with 10. As if statement is false, control jumps to else if statement checking another value with x and so on. public class Test { public static void main(String args[]) { int x = 30; if( x == 10 ) { System.out.print(“Value of X is 10”); }else if( x == 20 ) { System.out.print(“Value of X is 20”); }else if( x == 30 ) { System.out.print(“Value of X is 30”); }else { System.out.print(“This is else statement”); } } } Output Value of X is 30 Example 2: Java if … else if … else statement In this example, we”re showing the usage of if…else if…else statement. We”ve created a variable x and initialized it to 30.0. Then in the if statement, we”re checking x with 10,0. As if statement is false, control jumps to else if statement checking another value with x and so on. public class Test { public static void main(String args[]) { double x = 30.0; if( x == 10.0 ) { System.out.print(“Value of X is 10.0”); }else if( x == 20.0 ) { System.out.print(“Value of X is 20.0”); }else if( x == 30.0 ) { System.out.print(“Value of X is 30.0”); }else { System.out.print(“This is else statement”); } } } Output Value of X is 30.0 Java Nested if-else Statement The nested if else statement is used for better decision-making when other conditions are to be checked when a given condition is true. In the nested if else statement, you can have an if-else statement block the another if (or, else) block. Syntax of nested if-else statement Below is the syntax of nested if else statement: if(condition1){ // code block if(condition2){ //code block } } Example: Java Nested if else Statement The following examples finds the largest number among three using nested if..else statement. public class Test { public static void main(String[] args) { int x = 10, y = 20, z = 30; if(x >= y) { if(x >= z) System.out.println(x + ” is the largest.”); else System.out.println(z + ” is the largest.”); } else { if(y >= z) System.out.println(y + ” is the largest.”); else System.out.println(z + ” is the largest.”); } } } Output 30 is the largest. java_decision_making.htm Print Page Previous Next Advertisements ”;
Category: Java
Java – Variables Scope
Java – Variable Scopes ”; Previous Next The variable”s scope refers to the region where they are created and accessed in a given program or function. The variable scope also refers to its lifetime. In this tutorial, we will learn about the scopes of the different types of Java variables. Scope of Java Instance Variables A variable which is declared inside a class and outside all the methods and blocks is an instance variable. The general scope of an instance variable is throughout the class except in static methods. The lifetime of an instance variable is until the object stays in memory. Example: Scope of Java Instance Variables In the example below, we define an instance variable puppyAge in Puppy class and using its setAge(), we”re modifying it and using getAge() method, we”re getting it. This variable is available till the lifetime of myPuppy object instance. package com.tutorialspoint; public class Puppy { private int puppyAge; public void setAge( int age ) { // access the instance variable and modify it puppyAge = age; } public int getAge( ) { // access the instance variable return puppyAge; } public static void main(String []args) { Puppy myPuppy = new Puppy(); myPuppy.setAge( 2 ); System.out.println(“Puppy Age :” + myPuppy.getAge() ); } } Compile and run the program. This will produce the following result − Output Puppy Age :2 Scope of Java Local Variables A variable which is declared inside a class, outside all the blocks and is marked static is known as a class variable. The general scope of a class variable is throughout the class and the lifetime of a class variable is until the end of the program or as long as the class is loaded in memory. Example: Scope of Java Local Variables In the example below, we define a class variable BREED in Puppy class. This variable is available till the lifetime of program. Being static in nature, we can access it using class name directly as shown below: package com.tutorialspoint; public class Puppy { private int puppyAge; public static String BREED=”Bulldog”; public void setAge( int age ) { // access the instance variable and modify it puppyAge = age; } public int getAge( ) { // access the instance variable return puppyAge; } public static void main(String []args) { Puppy myPuppy = new Puppy(); myPuppy.setAge( 2 ); System.out.println(“Puppy Age :” + myPuppy.getAge() ); // access the class variable System.out.println(“Breed :” + Puppy.BREED ); } } Compile and run the program. This will produce the following result − Output Puppy Age :2 Breed :Bulldog Scope of Java Class (Static) Variables All other variables which are not instance and class variables are treated as local variables including the parameters in a method. Scope of a local variable is within the block in which it is declared and the lifetime of a local variable is until the control leaves the block in which it is declared. Example: Scope of Java Class (Static) Variables In the example below, we define two local varables in main() method of Puppy class. These variables are availble till the lifetime of method/block in which these are declared and can be accessed as shown below: package com.tutorialspoint; public class Puppy { private int puppyAge; public static String BREED=”Bulldog”; public void setAge( int age ) { // access the instance variable and modify it puppyAge = age; } public int getAge( ) { // access the instance variable return puppyAge; } public static void main(String []args) { Puppy myPuppy = new Puppy(); myPuppy.setAge( 2 ); System.out.println(“Puppy Age :” + myPuppy.getAge() ); // access the class variable System.out.println(“Breed :” + Puppy.BREED ); // local variables int a = 10; int b = 20; int c = a + b; System.out.println(“c: ” + c); } } Compile and run the program. This will produce the following result − Output Puppy Age :2 Breed :Bulldog c: 30 Important Points About Variables Scope By default, a variable has default access. Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public. Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are − default − Visible to the package. No modifiers are needed. private − Visible to the class only. public − Visible to the world. protected − Visible to the package and all subclasses. Print Page Previous Next Advertisements ”;
Java – Inheritance
Java – Inheritance ”; Previous Next Java Inheritance In Java programming, the inheritance is an important of concept of Java OOPs. Inheritance is a process where one class acquires the properties (methods and attributes) of another. With the use of inheritance, the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). Need of Java Inheritance Code Reusability: The basic need of an inheritance is to reuse the features. If you have defined some functionality once, by using the inheritance you can easily use them in other classes and packages. Extensibility: The inheritance helps to extend the functionalities of a class. If you have a base class with some functionalities, you can extend them by using the inheritance in the derived class. Implantation of Method Overriding: Inheritance is required to achieve one of the concepts of Polymorphism which is Method overriding. Achieving Abstraction: Another concept of OOPs that is abstraction also needs inheritance. Implementation of Java Inheritance To implement (use) inheritance in Java, the extends keyword is used. It inherits the properties (attributes or/and methods) of the base class to the derived class. The word “extends” means to extend functionalities i.e., the extensibility of the features. Syntax to implement inheritance Consider the below syntax to implement (use) inheritance in Java: class Super { ….. ….. } class Sub extends Super { ….. ….. } Java Inheritance Example Following is an example demonstrating Java inheritance. In this example, you can observe two classes namely Calculation and My_Calculation. Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of Calculation class. Copy and paste the following program in a file with name My_Calculation.java Java Program to Implement Inheritance class Calculation { int z; public void addition(int x, int y) { z = x + y; System.out.println(“The sum of the given numbers:”+z); } public void Subtraction(int x, int y) { z = x – y; System.out.println(“The difference between the given numbers:”+z); } } public class My_Calculation extends Calculation { public void multiplication(int x, int y) { z = x * y; System.out.println(“The product of the given numbers:”+z); } public static void main(String args[]) { int a = 20, b = 10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); demo.multiplication(a, b); } } Compile and execute the above code as shown below. javac My_Calculation.java java My_Calculation After executing the program, it will produce the following result − Output The sum of the given numbers:30 The difference between the given numbers:10 The product of the given numbers:200 In the given program, when an object to My_Calculation class is created, a copy of the contents of the superclass is made within it. That is why, using the object of the subclass you can access the members of a superclass. The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass. If you consider the above program, you can instantiate the class as given below. But using the superclass reference variable ( cal in this case) you cannot call the method multiplication(), which belongs to the subclass My_Calculation. Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. Java Inheritance: The super Keyword The super keyword is similar to this keyword. Following are the scenarios where the super keyword is used. It is used to differentiate the members of superclass from the members of subclass, if they have same names. It is used to invoke the superclass constructor from subclass. Differentiating the Members If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below. super.variable super.method(); Sample Code This section provides you a program that demonstrates the usage of the super keyword. In the given program, you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes. Here you can observe that we have used super keyword to differentiate the members of superclass from subclass. Copy and paste the program in a file with name Sub_class.java. Example class Super_class { int num = 20; // display method of superclass public void display() { System.out.println(“This is the display method of superclass”); } } public class Sub_class extends Super_class { int num = 10; // display method of sub class public void display() { System.out.println(“This is the display method of subclass”); } public void my_method() { // Instantiating subclass Sub_class sub = new Sub_class(); // Invoking the display() method of sub class sub.display(); // Invoking the display() method of superclass super.display(); // printing the value of variable num of subclass System.out.println(“value of the variable named num in sub class:”+ sub.num); // printing the value of variable num of superclass System.out.println(“value of the variable named num in super class:”+ super.num); } public static void main(String args[]) { Sub_class obj = new Sub_class(); obj.my_method(); } } Compile and execute the above code using the following syntax. javac Super_Demo java Super On executing the program, you will get the following result − Output This is the display method of subclass This is the display method of superclass value of the variable named num in sub class:10 value of the variable named num in super class:20 Invoking Superclass Constructor If a
Java – For-Each Loops
Java – for each Loop ”; Previous Next Java for each Loop A for each loop is a special repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times. A for each loop is useful even when you do not know how many times a task is to be repeated. Syntax Following is the syntax of enhanced for loop (or, for each loop) − for(declaration : expression) { // Statements } Execution Process Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element. Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array. Examples Example 1: Iterating Over a List of Integers In this example, we”re showing the use of a foreach loop to print contents of an List of Integers. Here we”re creating an List of integers as numbers and initialized it some values. Then using foreach loop, each number is printed. import java.util.Arrays; import java.util.List; public class Test { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50); for(Integer x : numbers ) { System.out.print( x ); System.out.print(“,”); } } } Output 10, 20, 30, 40, 50, Example 2: Iterating Over a List of Strings In this example, we”re showing the use of a foreach loop to print contents of an List of String. Here we”re creating an array of Strings as names and initialized it some values. Then using foreach loop, each name is printed. import java.util.Arrays; import java.util.List; public class Test { public static void main(String args[]) { List<String> names = Arrays.asList(“James”, “Larry”, “Tom”, “Lacy”); for( String name : names ) { System.out.print( name ); System.out.print(“,”); } } } Output James, Larry, Tom, Lacy, Example 3: Iterating Over an Array of Objects In this example, we”re showing the use of a foreach loop to print contents of an array of Student Object. Here we”re creating an array of Students as Student object and initialized it some values. Then using foreach loop, each name is printed. public class Test { public static void main(String args[]) { Student[] students = { new Student(1, “Julie”), new Student(3, “Adam”), new Student(2, “Robert”) }; for( Students student : students ) { System.out.print( student ); System.out.print(“,”); } } } class Student { int rollNo; String name; Student(int rollNo, String name){ this.rollNo = rollNo; this.name = name; } @Override public String toString() { return “[ ” + this.rollNo + “, ” + this.name + ” ]”; } } Output [ 1, Julie ],[ 3, Adam ],[ 2, Robert ], Print Page Previous Next Advertisements ”;
Java – Polymorphism
Java – Polymorphism ”; Previous Next Polymorphism in Java Polymorphism is the ability of an object to take on many forms. Polymorphism is an important feature of Java OOPs concept and it allows us to perform multiple operations by using the single name of any method (interface). Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for its own type and for the class Object. Use of Polymorphism in Java The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object. It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed. The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object. A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type. Java Polymorphism Example Let us look at an example. public interface Vegetarian{} public class Animal{} public class Deer extends Animal implements Vegetarian{} Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples − A Deer IS-A Animal A Deer IS-A Vegetarian A Deer IS-A Deer A Deer IS-A Object When we apply the reference variable facts to a Deer object reference, the following declarations are legal − Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; All the reference variables d, a, v, o refer to the same Deer object in the heap. Java Polymorphism Implementation In this example, we”re showcasing the above concept by creating the object of a Deer and assigning the same to the references of superclasses or implemented interface. interface Vegetarian{} class Animal{} public class Deer extends Animal implements Vegetarian{ public static void main(String[] args) { Deer d = new Deer(); Animal a = d; Vegetarian v = d; Object o = d; System.out.println(d instanceof Deer); System.out.println(a instanceof Deer); System.out.println(v instanceof Deer); System.out.println(o instanceof Deer); } } Output true true true true Types of Java Polymorphism There are two types of polymorphism in Java: Compile Time Polymorphism Run Time Polymorphism Compile Time Polymorphism in Java Compile-time polymorphism is also known as static polymorphism and it is implemented by method overloading. Example: Compile Time Polymorphism This example has multiple methods having the same name to achieve the concept of compile-time polymorphism in Java. // Java Example: Compile Time Polymorphism public class Main { // method to add two integers public int addition(int x, int y) { return x + y; } // method to add three integers public int addition(int x, int y, int z) { return x + y + z; } // method to add two doubles public double addition(double x, double y) { return x + y; } // Main method public static void main(String[] args) { // Creating an object of the Main method Main number = new Main(); // calling the overloaded methods int res1 = number.addition(444, 555); System.out.println(“Addition of two integers: ” + res1); int res2 = number.addition(333, 444, 555); System.out.println(“Addition of three integers: ” + res2); double res3 = number.addition(10.15, 20.22); System.out.println(“Addition of two doubles: ” + res3); } } Output Addition of two integers: 999 Addition of three integers: 1332 Addition of two doubles: 30.369999999999997 Run Time Polymorphism in Java Run time polymorphism is also known as dynamic method dispatch and it is implemented by the method overriding. Example: Run Time Polymorphism // Java Example: Run Time Polymorphism class Vehicle { public void displayInfo() { System.out.println(“Some vehicles are there.”); } } class Car extends Vehicle { // Method overriding @Override public void displayInfo() { System.out.println(“I have a Car.”); } } class Bike extends Vehicle { // Method overriding @Override public void displayInfo() { System.out.println(“I have a Bike.”); } } public class Main { public static void main(String[] args) { Vehicle v1 = new Car(); // Upcasting Vehicle v2 = new Bike(); // Upcasting // Calling the overridden displayInfo() method of Car class v1.displayInfo(); // Calling the overridden displayInfo() method of Bike class v2.displayInfo(); } } Output I have a Car. I have a Bike. Virtual Method and Run Time Polymorphism in Java In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes. We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method. Example: Implementation of Run Time Polymorphism with Virtual Methods /* File name : Employee.java */ public class Employee { private String name; private String address; private int number; public Employee(String name, String address, int number) { System.out.println(“Constructing an Employee”); this.name = name; this.address = address; this.number = number; } public void mailCheck() { System.out.println(“Mailing a check to ” + this.name + ” ” + this.address); } public String toString() { return name + ” ” + address + ” ” + number; } public String getName() { return name; } public String getAddress() { return address; } public void setAddress(String newAddress) { address = newAddress; } public int getNumber() { return number; } } Now suppose we extend Employee class as follows − /* File name : Salary.java */ public class Salary extends Employee { private double salary; // Annual salary public Salary(String name, String address, int number, double salary) { super(name, address, number); setSalary(salary); } public
Java – While Loops
Java – while Loop ”; Previous Next Java while Loop A while loop statement in Java programming language repeatedly executes a code block as long as a given condition is true. The while loop is an entry control loop, where condition is checked before executing the loop”s body. Syntax of while Loop The syntax of a while loop is − while(Boolean_expression) { // Statements } Execution Process of a while Loop Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non zero value. When executing, if the boolean_expression result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true. When the condition becomes false, program control passes to the line immediately following the loop. Flow Diagram The following diagram shows the flow diagram (execution process) of a while loop in Java – Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Examples of while Loop Example 1: Printing Numbers in a Range Using while Loop In this example, we”re showing the use of a while loop to print numbers starting from 10 to 19. Here we”ve initialized an int variable x with a value of 10. Then in while loop, we”re checking x as less than 20 and within while loop, we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 20. Once x is 20, loop will stop execution and program exits. public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { System.out.print(“value of x : ” + x ); x++; System.out.print(“n”); } } } Output value of x : 10 value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 15 value of x : 16 value of x : 17 value of x : 18 value of x : 19 Example 2: Printing Elements of an Array Using while Loop In this example, we”re showing the use of a while loop to print contents of an array. Here we”re creating an array of integers as numbers and initialized it some values. We”ve created a variable named index to represent index of the array while iterating it. In while loop we”re checking the index to be less than size of the array and printed the element of the array using index notation. index variable is incremented by 1 and loop continues till index becomes the sie of the array and loop exits. public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; int index = 0; while( index < 5 ) { System.out.print(“value of item : ” + numbers[index] ); index++; System.out.print(“n”); } } } Output value of item : 10 value of item : 20 value of item : 30 value of item : 40 value of item : 50 Infinite While Loop in Java You can implement an infinite while loop using the while loop statement by providing “true” as the test condition. Example 3: Implementing Nested while Loop In this example, we”re showing the infinite loop using while loop. It will keep printing the numbers until you press ctrl+c to terminate the program. public class Test { public static void main(String args[]) { int x = 10; while( true ) { System.out.print(“value of x : ” + x ); x++; System.out.print(“n”); } } } Output value of item : 10 value of item : 20 value of item : 30 value of item : 40 value of item : 50 … ctrl+c java_loop_control.htm Print Page Previous Next Advertisements ”;
Java – User Input
Java – User Input ”; Previous Next User Input in Java To take input from the user in Java, the Scanner class is used. The Scanner class a built-in class of java.util package. Java Scanner class provides many built-in methods to take different types of user inputs from the users. How to Use Scanner Class to Take User Input? The following are the steps to use Scanner class for the user input in Java − Step 1: Import Scanner Class Fist you need to import the Scanner class to use its methods. To import the Scanner class, use the following import statement − import java.util.Scanner Step 2: Create Scanner Class”s Object After importing the Scanner class, you need to create its object to use its methods. To create an object of the Scanner class, invoke Scanner() constructor. Below is the statement to create an object of Scanner class − Scanner obj = new Scanner(System.in); Step 3: Take User Input Scanner class provides a variety of methods which are useful to take user input of different types. For example, if you want to input an integer value, use nextInt() method. The following is the statement to take user input in Java − int age = obj.nextInt(); The above statement will wait for an integer input from the user. When user provides an integer value, that will be assign to “age” variable. Example of User Input in Java In the following example, we are reading two integers from the user, calculating, and printing their addition − // Importing the class import java.util.Scanner; public class AddTwoNumbers { public static void main(String[] args) { // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Reading two Integer numbers // using nextInt() method System.out.print(“Enter the first number: “); int num1 = sc.nextInt(); System.out.print(“Enter the second number: “); int num2 = sc.nextInt(); // Calculating the sum int sum = num1 + num2; // Printing the su System.out.println(“The sum of the two numbers is: ” + sum); } } Output Enter the first number: 10 Enter the second number: 20 The sum of the two numbers is: 30 Methods for Different Types of User Inputs The Scanner class provides different methods for the different types of User inputs. To explore all methods for different user inputs, look at the table below − Sr.No. Method & Description 1 String next() This method finds and returns the next complete token from this scanner. 2 BigDecimal nextBigDecimal() This method scans the next token of the input as a BigDecimal. 3 BigInteger nextBigInteger() This method Scans the next token of the input as a BigInteger. 4 boolean nextBoolean() This method scans the next token of the input into a boolean value and returns that value. 5 byte nextByte() This method scans the next token of the input as a byte. 6 double nextDouble() This method scans the next token of the input as a double. 7 float nextFloat() This method scans the next token of the input as a float. 8 int nextInt() This method scans the next token of the input as an int. 9 String nextLine() This method advances this scanner past the current line and returns the input that was skipped. 10 long nextLong() This method scans the next token of the input as a long. 11 short nextShort() This method scans the next token of the input as a short. Integer Input from the User The nextInt() method is used to take input of an integer from the user. Example In the following example, we are taking an integer as an input − // Importing the class import java.util.Scanner; public class IntegerInput { public static void main(String[] args) { // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Reading an Integer Input System.out.print(“Input an integer value: “); int int_num = sc.nextInt(); System.out.print(“The input is : ” + int_num); } } Output Input an integer value: 101 The input is : 101 Float Input from the User The nextFloat() method is used to take input of a float value from the user. Example In the following example, we are taking a float as an input − // Importing the class import java.util.Scanner; public class IntegerInput { public static void main(String[] args) { // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Reading a Float Input System.out.print(“Input a float value: “); float float_num = sc.nextFloat(); System.out.print(“The input is : ” + float_num); } } Output Input a float value: 12.345 The input is : 12.345 String Input from the User The nextLine() method is used to take input of a float value from the user. Example In the following example, we are taking a string as an input − // Importing the class import java.util.Scanner; public class IntegerInput { public static void main(String[] args) { // Creating an object of Scanner class Scanner sc = new Scanner(System.in); // Reading a String Input System.out.print(“Input a string value: “); String str = sc.nextLine(); System.out.print(“The input is : ” + str); } } Output Input a string value: Hello World The input is : Hello World Print Page Previous
Java – Date & Time
Java – Date and Time ”; Previous Next Java provides the Date class available in java.util package, this class encapsulates the current date and time. The Date class supports two constructors as shown in the following table. Sr.No. Constructor & Description 1 Date( ) This constructor initializes the object with the current date and time. 2 Date(long millisec) This constructor accepts an argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970. Following are the methods of the date class. Sr.No. Method & Description 1 boolean after(Date when) This method tests if this date is after the specified date. 2 boolean before(Date when) This method tests if this date is before the specified date. 3 Object clone() This method return a copy of this object. 4 int compareTo(Date anotherDate) This method compares two Dates for ordering. 5 boolean equals(Object obj) This method compares two dates for equality. 6 static Date from(Instant instant) This method obtains an instance of Date from an Instant object. 7 long getTime() This method returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. 8 int hashCode() This method returns a hash code value for this object. 9 void setTime(long time) This method sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT. 10 Instant toInstant() This method converts this Date object to an Instant. 11 String toString() This method converts this Date object to a String of the form. Getting Current Date and Time This is a very easy method to get current date and time in Java. You can use a simple Date object with toString() method to print the current date and time as follows − Example import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date using toString() System.out.println(date.toString()); } } This will produce the following result − Output on May 04 09:51:52 CDT 2009 Date Comparison Following are the three ways to compare two dates − You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values. You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true. You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date. Date Formatting Using SimpleDateFormat SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. Example import java.util.*; import java.text.*; public class DateDemo { public static void main(String args[]) { Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat (“E yyyy.MM.dd ”at” hh:mm:ss a zzz”); System.out.println(“Current Date: ” + ft.format(dNow)); } } This will produce the following result − Output Current Date: Sun 2004.07.18 at 04:14:09 PM PDT Simple DateFormat Format Codes To specify the time format, use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, which are defined as the following − Character Description Example G Era designator AD y Year in four digits 2001 M Month in year July or 07 d Day in month 10 h Hour in A.M./P.M. (1~12) 12 H Hour in day (0~23) 22 m Minute in hour 30 s Second in minute 55 S Millisecond 234 E Day in week Tuesday D Day in year 360 F Day of week in month 2 (second Wed. in July) w Week in year 40 W Week in month 1 a A.M./P.M. marker PM k Hour in day (1~24) 24 K Hour in A.M./P.M. (0~11) 10 z Time zone Eastern Standard Time ” Escape for text Delimiter “ Single quote ` Date Formatting Using printf Date and time formatting can be done very easily using printf method. You use a two-letter format, starting with t and ending in one of the letters of the table as shown in the following code. Example import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date String str = String.format(“Current Date/Time : %tc”, date ); System.out.printf(str); } } This will produce the following result − Output Current Date/Time : Sat Dec 15 16:37:57 MST 2012 It would be a bit silly if you had to supply the date multiple times to format each part. For that reason, a format string can indicate the index of the argument to be formatted. The index must immediately follow the % and it must be terminated by a $. Example import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display time and date System.out.printf(“%1$s %2$tB %2$td, %2$tY”, “Due date:”, date); } } This will produce the following result − Output Due date: February 09, 2004 Alternatively, you can use the < flag. It indicates that the same argument as in the preceding format specification should be used again. Example import java.util.Date; public class DateDemo { public static void main(String args[]) { // Instantiate a Date object Date date = new Date(); // display formatted date System.out.printf(“%s %tB %<te, %<tY”, “Due date:”, date); } } This will produce the following result − Output Due date: February 09, 2004 Date and Time Conversion Characters Character Description Example c Complete date and time Mon May 04 09:51:52 CDT 2009 F ISO 8601 date 2004-02-09 D U.S. formatted date (month/day/year) 02/09/2004 T 24-hour time 18:05:19 r 12-hour time 06:05:19 pm R 24-hour time, no seconds 18:05 Y Four-digit year (with leading zeroes) 2004 y Last two digits of the year
Java – Continue
Java – continue Statement ”; Previous Next Java continue Statement The continue statement can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes control to immediately jump to the update statement. In a while loop or do/while loop, control immediately jumps to the Boolean expression. Syntax The syntax of a continue is a single statement inside any loop − continue; Flow Diagram Examples Example 1: Using continue with while loop In this example, we”re showing the use of a continue statement to skip an element 15 in a while loop which is used to print element from 10 to 19. Here we”ve initialized an int variable x with a value of 10. Then in while loop, we”re checking x as less than 20 and within while loop, we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 15. Once x is 15, continue statement will jump the while loop while skipping the execution of the body and loop continues. public class Test { public static void main(String args[]) { int x = 10; while( x < 20 ) { x++; if(x == 15){ continue; } System.out.print(“value of x : ” + x ); System.out.print(“n”); } } } Output value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 16 value of x : 17 value of x : 18 value of x : 19 value of x : 20 Example 2: Using continue with for loop In this example, we”re showing the use of a continue statement within a for loop to skip an elements of an array to print. Here we”re creating an array of integers as numbers and initialized it some values. We”ve created a variable named index to represent index of the array within for loop, check it against size of the array and incremented it by 1. Within for loop body, we”re printing element of the array using index notation. Once 30 is encountered as value, continue statement jumps to the update section of for loop and loop continues. public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int index = 0; index < numbers.length; index++) { if(numbers[index] == 30){ continue; } System.out.print(“value of item : ” + numbers[index] ); System.out.print(“n”); } } } Output value of item : 10 value of item : 20 value of item : 40 value of item : 50 Example 3: Using continue with do while loop In this example, we”re showing the use of a continue statement to skip an element 15 in a do while loop which is used to print element from 10 to 19. Here we”ve initialized an int variable x with a value of 10. Then in do while loop, we”re checking x as less than 20 after body and within while loop, we”re printing the value of x and incrementing the value of x by 1. While loop will run until x becomes 15. Once x is 15, continue statement will jump the while loop while skipping the execution of the body and loop continues. public class Test { public static void main(String args[]) { int x = 10; do { x++; if(x == 15){ continue; } System.out.print(“value of x : ” + x ); System.out.print(“n”); } while( x < 20 ); } } Output value of x : 11 value of x : 12 value of x : 13 value of x : 14 value of x : 16 value of x : 17 value of x : 18 value of x : 19 value of x : 20 java_loop_control.htm Print Page Previous Next Advertisements ”;
Java – Access Modifiers
Java – Access Modifiers ”; Previous Next Java access modifiers are used to specify the scope of the variables, data members, methods, classes, or constructors. These help to restrict and secure the access (or, level of access) of the data. There are four different types of access modifiers in Java, we have listed them as follows: Default (No keyword required) Private Protected Public Default Access Modifier Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public. Example of Default Access Modifiers Variables and methods can be declared without any modifiers, as in the following examples − String version = “1.5.1”; boolean processOrder() { return true; } Private Access Modifier Methods, variables, and constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level. Class and interfaces cannot be private. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world. Examples of Private Access Modifiers Example 1 The following class uses private access control − public class Logger { private String format; public String getFormat() { return this.format; } public void setFormat(String format) { this.format = format; } } Here, the format variable of the Logger class is private, so there”s no way for other classes to retrieve or set its value directly. So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value. Example 2 In this example, the data members and class methods of the Logger class are private. We are trying to access those class methods in another class Main. class Logger { private String format; private String getFormat() { return this.format; } private void setFormat(String format) { this.format = format; } } public class Main { public static void main(String[] args) { // Creating an object Logger log = new Logger(); // Setting the value log.setFormat(“Text”); // Getting the value System.out.println(log.getFormat()); } } Output Main.java:18: error: setFormat(String) has private access in Logger log.setFormat(“Text”); ^ Main.java:20: error: getFormat() has private access in Logger System.out.println(log.getFormat()); ^ 2 errors Protected Access Modifier Variables, methods, and constructors, which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members” class. The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected. Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. Examples of Protected Access Modifiers Example 1 The following parent class uses protected access control, to allow its child class override openSpeaker() method − class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // implementation details } } class StreamingAudioPlayer extends AudioPlayer { boolean openSpeaker(Speaker sp) { // implementation details } } Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that”s why we have used protected modifier. Example 1 This example demonstrates the use of protected access modifier. // Class One class One { protected void printOne() { System.out.println(“printOne method of One class.”); } } // Inheriting class One on Main public class Main extends One { public static void main(String[] args) { // Creating an object of Main class Main obj = new Main(); // Calling printOne() method of class One // through the object of Main class obj.printOne(); } } Output printOne method of One class. Public Access Modifier A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe. However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. Syntax The following function uses public access control − public static void main(String[] arguments) { // … } The main() method of an application has to be public. Otherwise, it could not be called by a Java interpreter (such as java) to run the class. Example of Public Access Modifiers This example demonstrates the use of public access modifier. // Class One class One { public void printOne() { System.out.println(“printOne method of One class.”); } } public class Main { public static void main(String[] args) { // Creating an object of class One One obj = new One(); // Calling printOne() method of class One obj.printOne(); } } Output This example demonstrates the use of public access modifier. Access Modifiers and Inheritance The following rules for inherited methods are enforced − Methods declared public in a superclass also must be public in all subclasses. Methods declared protected in a superclass must either be protected or public in subclasses; they cannot be private. Methods declared private are not inherited at all, so there is no rule for them. The following table shows the summary of the accessibility in the same/different classes (or, packages) based on the access modifiers. Example of Access Modifiers with Inheritance In this example, we”ve created a class with a private variable age and