Java – Packages

Java – Packages ”; Previous Next Java Packages Packages are used in Java in order to prevent naming conflicts, control access, make searching/locating and usage of classes, interfaces, enumerations, and annotations easier, etc. A Java package can be defined as a grouping of related types (classes, interfaces, enumerations, and annotations ) providing access protection and namespace management. Types of Java Packages Java packages are of two types: Built-in Java Packages User-defined Java Packages Some of the existing packages in Java are − java.lang − bundles the fundamental classes java.io − classes for input , output functions are bundled in this package User-defined Java Packages You can define your own packages to bundle groups of classes/interfaces, etc. It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related. Since the package creates a new namespace there won”t be any name conflicts with names in other packages. Using packages, it is easier to provide access control and it is also easier to locate the related classes. Creating a Java Package While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file. If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. Compiling with Java Package To compile the Java programs with package statements, you have to use -d option as shown below. javac -d Destination_folder file_name.java Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder. Java Package Example Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces. Following package example contains interface named animals − /* File name : Animal.java */ package animals; interface Animal { public void eat(); public void travel(); } Now, let us implement the above interface in the same package animals − package animals; /* File name : MammalInt.java */ public class MammalInt implements Animal { public void eat() { System.out.println(“Mammal eats”); } public void travel() { System.out.println(“Mammal travels”); } public int noOfLegs() { return 0; } public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } interface Animal { public void eat(); public void travel(); } Output Now compile the java files as shown below − $ javac -d . Animal.java $ javac -d . MammalInt.java Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below. You can execute the class file within the package and get the result as shown below. Mammal eats Mammal travels Importing Java Package If a class wants to use another class in the same package, the package name need not be used. Classes in the same package find each other without any special syntax. Example Here, a class named Boss is added to the payroll package that already contains Employee. The Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by the following Boss class. package payroll; public class Boss { public void payEmployee(Employee e) { e.mailCheck(); } } What happens if the Employee class is not in the payroll package? The Boss class must then use one of the following techniques for referring to a class in a different package. The fully qualified name of the class can be used. For example − payroll.Employee The package can be imported using the import keyword and the wild card (*). For example − import payroll.*; The class itself can be imported using the import keyword. For example − import payroll.Employee; Example package payroll; public class Employee { public void mailCheck() { System.out.println(“Pay received.”); } } Example package payroll; import payroll.Employee; public class Boss { public void payEmployee(Employee e) { e.mailCheck(); } public static void main(String[] args) { Boss boss = new Boss(); Employee e = new Employee(); boss.payEmployee(e); } } Output Pay received. Note − A class file can contain any number of import statements. The import statements must appear after the package statement and before the class declaration. Directory Structure of a Java Package Two major results occur when a class is placed in a package − The name of the package becomes a part of the name of the class, as we just discussed in the previous section. The name of the package must match the directory structure where the corresponding bytecode resides. Here is simple way of managing your files in Java − Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example − // File Name : Car.java package vehicle; public class Car { // Class implementation. } Now, put the source file in a directory whose name reflects the name of the package to which the class belongs − ….vehicleCar.java Now, the qualified class name and pathname would be as follows − Class name → vehicle.Car Path name → vehicleCar.java (in windows) In general, a company uses its reversed Internet domain name for its package names. Example − A company”s Internet domain name is apple.com, then all its package names would start with com.apple. Each component of the package name corresponds to a subdirectory. Example − The company had a com.apple.computers package that contained

Java – Instance Initializer Block

Java – Instance Initializer Block ”; Previous Next Java Instance Initializer Block An instance initializer block is a block of code that is declared inside a class to initialize the instance data members. Instance Initializer block is executed once for each object and can be used to set initial values for instance variables. The instance initializer block is similar to the Java constructor but its execution and uses are different. Java Instance Initializer Block Example This example demonstrates instance initializer block in Java: public class Tester { public int a; { a = 10; } } Characteristics of Instance Initializer Block Instance initializer block is called once an object is created. Instance initializer block is called before any constructor of an object is invoked. In case of child class, Instance initializer block will be called after super class constructor call. Instance initializer block can be used to execute multiple statements. Instance initializer block is generally used to instantiate multiple values fields like arrays. Use of Instance Initializer Block The following are the uses of instance initializer block in Java: To initialize the instance variable. To initialize the resources used in the code. To perform the dynamic initialization of the instance variables. To use the common initialization logic for multiple constructors. Java Instance Initializer Block: More Examples Example 1: Demonstrating What Invokes First, Instance Initializer Block or Constructor In this example, we”ve shown that instance initializer block is getting executed before the object constructor. Both instance initializer block and constructor are invoked when object is created using new operator. package com.tutorialspoint; public class Tester { { System.out.println(“Inside instance initializer block”); } Tester(){ System.out.println(“Inside constructor”); } public static void main(String[] arguments) { Tester test = new Tester(); } } Output 60 150 Example 2: Demonstrating Whether Constructor Overrides Instance Initializer Block In this example, we”ve shown that a value initialized in instance initializer block is getting overriden by the object constructor. Both instance initializer block and constructor are invoked when object is created using new operator. package com.tutorialspoint; public class Tester { int a; { System.out.println(“Inside instance initializer block”); a = 10; } Tester(){ System.out.println(“Inside constructor”); a = 20; } public static void main(String[] arguments) { Tester test = new Tester(); System.out.println(“Value of a: ” + a); } } Output Inside instance initializer block Inside constructor Value of a: 20 Example 3: Instance Initializer Block and Super Constructor In this example, we”ve shown that a super constructor is invoked before child instance initializer block. We”ve created a SuperTester class and Tester class extends this class. In main() method, we”re printing the value of instance variable. In output, you can verify the order of blocks invoked. First super constructor is invoked. Then child instance initializer is invoked which initializes an instance variable and then constructor of child class is invoked. package com.tutorialspoint; class SuperTester{ SuperTester(){ System.out.println(“Inside super constructor”); } } public class Tester extends SuperTester { int a; { System.out.println(“Inside instance initializer block”); a = 10; } Tester(){ System.out.println(“Inside constructor”); } public static void main(String[] arguments) { Tester test = new Tester(); System.out.println(“Value of a: ” + test.a); } } Output Inside super constructor Inside instance initializer block Inside constructor Value of a: 10 Print Page Previous Next Advertisements ”;

Java – Static Binding

Java – Static Binding ”; Previous Next Binding is a mechanism creating link between method call and method actual implementation. As per the polymorphism concept in Java, object can have many different forms. Object forms can be resolved at compile time and run time. Java Static Binding Static binding refers to the process in which linking between method call and method implementation is resolved at compile time. Static binding is also known as compile-time binding or early binding. Characteristics of Java Static Binding Linking − Linking between method call and method implementation is resolved at compile time. Resolve mechanism − Static binding uses type of the class and fields to resolve binding. Example − Method overloading is the example of Static binding. Type of Methods − private, final and static methods and variables uses static binding. Example of Java Static Binding In this example, we”ve created a Calculator class having two static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods and printing the result. Based on the number of arguments passed, compiler decides the method using static binding which method is to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ System.out.println(Calculator.add(20, 40)); System.out.println(Calculator.add(40, 50, 60)); } } Output 60 150 Java Static Binding: More Examples Example 1 In this example, we”ve created a Calculator class having two non-static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the number of arguments passed, compiler decides the method using static binding which method is to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(40, 50, 60)); } } Output 60 150 Example 2 In this example, we”ve created a Calculator class having two non-static methods with same name but different types of arguments to add two int values and two double values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the type of arguments passed, compiler decides the method using static binding which method is to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public double add(double a, double b){ return a + b; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(20.0, 40.0)); } } Output 60 60.0 Print Page Previous Next Advertisements ”;

Java – Exception Propagation

Java – Exception Propagation ”; Previous Next Exception Propagation Exception propagation refers to movement of exception event from nested try or nested methods calls. A try block can be nested within another try block. Similarly a method can call another method where each method can handle exception independently or can throw checked/unchecked exceptions. Whenever an exception is raised within a nested try block/method, its exception is pushed to Stack. The exception propagates from child to parent try block or from child method to parent method and so on. Syntax – Nested Try Block The syntax for nested catch blocks looks like the following − try { // parent try block try { // child try block } catch(ExceptionType1 e1){ // child catch block } } catch (ExceptionType2 e1) { // parent catch block } Syntax – Nested Method Calls The syntax for nested method calls looks like the following − method1(){ // parent method try { // parent try block method2(); } catch (ExceptionType2 e1) { // parent catch block } method2(){ // child method // code to throw Exception // this exception will be handled by parent method } The previous statements demonstrate two try/catch blocks and methods, but you can have any number of them. If an exception occurs in the protected child code, the exception is thrown to the catch block of the child list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes up to the parent catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. Rules for Exception Propagation in Java Child catch block should have specific exception for better code clarity. Parent catch block can have more generic exception handled so that if child catch block is not able to handle the exception then parent catch block can handle it. There in no restriction on exception hiearchy to be used in child vs parent catch block. If a exception is handled correctly in child catch block, then in parent, another exception can be raised and handled. Java Exception Propagation Example Here is code segment showing exception event propagation from child to parent. In this example, we”re creating an error by dividing a value by 0 in a child method. The child method throws the exception. Now in parent method, in try block, we”re handling the exception and printing the error message. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; try { System.out.println(“result:” + divide(a,b)); }catch(ArithmeticException e) { System.out.println(e.getMessage()); } } private static int divide(int a, int b) { return a / b; } } Output / by zero More Examples Example 1 Here is code segment showing exception event propagation from child to parent. In this example, we”re creating an error by dividing a value by 0 in a child method. The child method throws the exception. Now in parent method, we”re not handling the exception. The JVM will intercept the exception and prints the error message. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; System.out.println(“result:” + divide(a,b)); } private static int divide(int a, int b) { return a / b; } } Output Exception in thread “main” java.lang.ArithmeticException: / by zero at com.tutorialspoint.ExcepTest.divide(ExcepTest.java:12) at com.tutorialspoint.ExcepTest.main(ExcepTest.java:8) Example 2 Here is code segment showing exception event propagation to stop within child itself instead of flowing to parent. In this example, we”re creating an error by dividing a value by 0 in a child method. The child method is handling the exception. Now in parent method, we”re not getting any exception. package com.tutorialspoint; public class ExcepTest { public static void main(String args[]) { int a = 3; int b = 0; System.out.println(“result:” + divide(a,b)); } private static int divide(int a, int b) { try { return a / b; }catch(ArithmeticException e) { System.out.println(e.getMessage()); } return 0; } } Output / by zero result:0 Print Page Previous Next Advertisements ”;

Java – Encapsulation

Java – Encapsulation ”; Previous Next Java Encapsulation Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. Achieving Encapsulation in Java To achieve encapsulation in Java − Declare the variables of a class as private. Provide public setter and getter methods to modify and view the variables values. Java Encapsulation Example Following is an example that demonstrates how to achieve Encapsulation in Java − /* File name : EncapTest.java */ public class EncapTest { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be accessed using the following program − /* File name : RunEncap.java */ public class RunEncap { public static void main(String args[]) { EncapTest encap = new EncapTest(); encap.setName(“James”); encap.setAge(20); encap.setIdNum(“12343ms”); System.out.print(“Name : ” + encap.getName() + ” Age : ” + encap.getAge()); } } public class EncapTest { private String name; private String idNum; private int age; public int getAge() { return age; } public String getName() { return name; } public String getIdNum() { return idNum; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; } public void setIdNum( String newId) { idNum = newId; } } Output Name : James Age : 20 Benefits of Encapsulation The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields. Java Encapsulation: Read-Only Class A read-only class can have only getter methods to get the values of the attributes, there should not be any setter method. Example: Creating Read-Only Class In this example, we defined a class Person with two getter methods getName() and getAge(). These methods can be used to get the values of attributes declared as private in the class. // Class “Person” class Person { private String name = “Robert”; private int age = 21; // Getter methods public String getName() { return this.name; } public int getAge() { return this.age; } } public class Main { public static void main(String args[]) { // Object to Person class Person per = new Person(); // Getting and printing the values System.out.println(“Name of the person is: ” + per.getName()); System.out.println(“Age of the person is: ” + per.getAge()); } } Output Name of the person is: Robert Age of the person is: 21 Java Encapsulation: Write-Only Class A write-only class can have only setter methods to set the values of the attributes, there should not be any getter method. Example: Creating Write-Only Class In this example, we defined a class Person with two setter methods setName() and setAge(). These methods can be used to set the values of attributes declared as private in the class. // Class “Person” class Person { private String name; private int age; // Setter Methods public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } } public class Main { public static void main(String args[]) { // Object to Person class Person per = new Person(); // Setting the values per.setName(“Robert”); per.setAge(21); } } Java Encapsulation: More Examples Example 1: Person Class (Fully Encapsulated) This example creates a fully encapsulated class named “Person”. This class has private class attributes, setter, and getter methods. // Class “Person” class Person { private String name; private int age; // Setter Methods public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } // Getter methods public String getName() { return this.name; } public int getAge() { return this.age; } } // The Main class to test encapsulated class “Person” public class Main { public static void main(String args[]) { // Objects to Person class Person per1 = new Person(); Person per2 = new Person(); // Setting the values per1.setName(“Robert”); per1.setAge(21); per2.setName(“Riyan”); per2.setAge(22); // Printing the values System.out.println(“Person 1: Name : ” + per1.getName() + ” Age : ” + per1.getAge()); System.out.println(“Person 2: Name : ” + per2.getName() + ” Age : ” + per2.getAge()); } } Output Person 1: Name : Robert Age : 21 Person 2: Name : Riyan Age : 22 Example 2: Employee Class (Fully Encapsulated) This example creates a fully encapsulated class named “Employee”. This class has private class attributes, setter, and getter methods. // Class “Employee” class Employee { private String emp_name; private String emp_id; private double net_salary; // Constructor public Employee(String emp_name, String emp_id, double net_salary) { this.emp_name = emp_name; this.emp_id = emp_id; this.net_salary = net_salary; } // Getter methods public String getEmpName() { return emp_name; } public String getEmpId() { return emp_id; } public double getSalary() { return net_salary; } // Setter methods public void setEmpName(String emp_name) { this.emp_name = emp_name; } public void setEmpId(String emp_id) { this.emp_id = emp_id; } public void setSalary(double net_salary) { this.net_salary = net_salary; } } // The Main class to test encapsulated class “Employee” public class Main { public static void main(String args[]) { // Objects to Employee class // First object – setting values using constructor Employee emp = new Employee(“Robert”, “EMP001”, 75450.00);

Java – Method Overloading

Java – Method Overloading ”; Previous Next Java Method Overloading When a class has two or more methods by the same name but different parameters, at the time of calling based on the parameters passed respective method is called (or respective method body will be bonded with the calling line dynamically). This mechanism is known as method overloading. Advantage of Method Overloading Method overloading improves the code readability and reduces code redundancy. Method overloading also helps to achieve compile-time polymorphism. Example of Method Overloading If you observe the following example, Here we have created a class named Tester this class has two methods with same name (add) and return type, the only difference is the parameters they accept (one method accepts two integer variables and other accepts three integer variables). class Calculator{ public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } } When you invoke the add() method based on the parameters you pass respective method body gets executed. int result = Calculator.add(1,2); // returns 3; result = Calculator.add(1,2,3); // returns 6; Different Ways of Java Method Overloading Method overloading can be achieved using following ways while having same name methods in a class. Use different number of arguments Use different type of arguments Invalid Ways of Java Method Overloading Method overloading cannot be achieved using following ways while having same name methods in a class. Compiler will complain of duplicate method presence. Using different return type Using static and non-static methods Method Overloading: Different Number of Arguments You can implement method overloading based on the different number of arguments. Example: Different Number of Arguments (Static Methods) In this example, we”ve created a Calculator class having two static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods and printing the result. Based on the type of arguments passed, compiler decides the method to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ System.out.println(Calculator.add(20, 40)); System.out.println(Calculator.add(40, 50, 60)); } } Output 60 150 Example: Different Number of Arguments (Non Static Methods) In this example, we”ve created a Calculator class having two non-static methods with same name but different arguments to add two and three int values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the number of arguments passed, compiler decides the method to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public int add(int a, int b, int c){ return a + b + c; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(40, 50, 60)); } } Output 60 150 Method Overloading: Different Type of Arguments You can implement method overloading based on the different type of arguments. Example: Different Type of Arguments In this example, we”ve created a Calculator class having two non-static methods with same name but different types of arguments to add two int values and two double values respectively. In main() method, we”re calling these methods using object of Calculator class and printing the result. Based on the type of arguments passed, compiler decides the method to be called and result is printed accordingly. package com.tutorialspoint; class Calculator{ public int add(int a, int b){ return a + b; } public double add(double a, double b){ return a + b; } } public class Tester { public static void main(String args[]){ Calculator calculator = new Calculator(); System.out.println(calculator.add(20, 40)); System.out.println(calculator.add(20.0, 40.0)); } } Output 60 60.0 Print Page Previous Next Advertisements ”;

Java – Thread Scheduler

Java – Scheduling Threads with Examples ”; Previous Next Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs. By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. Java provides a java.util.concurrent.ScheduledExecutorService interface which is a subinterface of ExecutorService interface, and supports future and/or periodic execution of tasks/threads. Following are few important and useful methods this interface. ScheduledExecutorService Methods Sr.No. Method & Description 1 <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) Creates and executes a ScheduledFuture that becomes enabled after the given delay. 2 ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) Creates and executes a one-shot action that becomes enabled after the given delay. 3 ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. 4 ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next. Example 1 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedRate() and schedule() methods. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep beep beep beep beep Example 2 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run after 2 seconds at interval of 2 seconds in time period of 10 seconds showcasing usage of scheduleAtFixedDelay() and schedule() methods. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.scheduleAtFixedDelay(new BeepTask(), 2, 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep beep beep beep Example 3 The following TestThread program shows usage of ScheduledExecutorService interface in thread based environment to schedule a task to run once after 2 seconds in time period of 10 seconds showcasing usage of schedule() method. package com.tutorialspoint; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; public class TestThread { public static void main(final String[] arguments) throws InterruptedException { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final ScheduledFuture<?> beepHandler = scheduler.schedule(new BeepTask(), 2, TimeUnit.SECONDS); scheduler.schedule(new Runnable() { @Override public void run() { beepHandler.cancel(true); scheduler.shutdown(); } }, 10, TimeUnit.SECONDS); } static class BeepTask implements Runnable { public void run() { System.out.println(“beep”); } } } Output beep Print Page Previous Next Advertisements ”;

Java – Hello World Program

Java – Hello World Program ”; Previous Next Printing “Hello World” on the output screen (console) is the first program in Java and other programming languages. This tutorial will teach you how you can write your first program (print “Hello World” program) in Java programming. Java program to print “Hello World” Java program to print “Hello World” is given below: public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello World” as the output */ public static void main(String []args) { System.out.println(“Hello World”); // prints Hello World } } Steps to Write, Save, and Run Hello World Program Let”s look at how to save the file, compile, and run the program. Please follow the subsequent steps − Open notepad and add the code as above. Save the file as − “MyFirstJavaProgram.java”. Open a command prompt window and go to the directory where you saved the class. Assume it”s C:. Type ”javac MyFirstJavaProgram.java” and press enter to compile your code. If there is no error in your code, the command prompt will take you to the next line (Assumption − The path variable is set. Learn: Java Envionment Setup). Now, type ”java MyFirstJavaProgram” to run your program. You will be able to see “Hello World” printed on the screen. Output C:> javac MyFirstJavaProgram.java C:> java MyFirstJavaProgram Hello World Explanation of Hello World Program As we”ve successfully printed Hello World on the output screen. Let”s understand the code line by line. 1. Public Main Class public class MyFirstJavaProgram { This line is creating a new class MyFirstJavaProgram and being public, this class is to be defined in the same name file as MyFirstJavaProgram.java. This convention helps Java compiler to identify the name of public class to be created before reading the file content. 2. Comment Section /* This is my first java program. * This will print ”Hello World” as the output */ These lines being in /* */ block are not considered by Java compiler and are comments. A comment helps to understand program in a better way and makes code readable and understandable. 3. Public Static Void Main public static void main(String []args) { This line represents the main method that JVM calls when this program is loaded into memory. This method is used to execute the program. Once this method is finished, program is finished in single threaded environment. 4. Keywords Used Let”s check the purpose of each keyword in this line. public − defines the scope of the main method. Being public, this method can be called by external program like JVM. static − defines the state of the main method. Being static, this method can be called by external program like JVM without first creating the object of the class. void − defines the return type of the main method. Being void, this method is not returning any value. main − name of the method String []args − arguments passed on command line while executing the java command. 5. System.out.println() Method System.out.println(“Hello World”); // prints Hello World System.out represents the primary console and its println() method is taking “Hello World” as input and it prints the same to the console output. Print Page Previous Next Advertisements ”;

Java – Unicode System

Java – Unicode System ”; Previous Next Unicode is an international character set that encompasses a vast range of characters, symbols, and scripts from many languages across the globe. Unicode System in Java Java programming language, being platform-independent, has built-in support for Unicode characters, allowing developers to create applications that can work seamlessly with diverse languages and scripts. Before Unicode, there were multiple standards to represent character encoding − ASCII − for the United States. ISO 8859-1 − for Western European Language. KOI-8 − for Russian. GB18030 and BIG-5 − for Chinese. So to support multinational application codes, some character was using single byte, some two. An even same code may represent a different character in one language and may represent other characters in another language. To overcome above shortcoming, the Unicode system was developed where each character is represented by 2 bytes. As Java was developed for multilingual languages it adopted the Unicode system. The lowest value is represented by u0000 and the highest value is represented by uFFFF. Approaches: Working with Unicode Characters & Values There are two approaches for working with Unicode characters in Java: Using Unicode Escape Sequences and Directly Storing Unicode Characters. The first approach involves representing Unicode characters using escape sequences and is useful when the characters cannot be directly typed or displayed in the Java code. The second approach involves directly storing Unicode characters in variables and is more convenient when the characters can be directly typed or displayed. The choice of approach depends on the specific requirements of the program. However, in general, Approach 2 is simpler and more convenient when the characters can be directly typed or displayed, while Approach 1 is necessary when they cannot. 1. Using Unicode Escape Sequences One way to store Unicode characters in Java is by using Unicode escape sequences. An escape sequence is a series of characters that represent a special character. In Java, a Unicode escape sequence starts with the characters ”u” followed by four hexadecimal digits that represent the Unicode code point of the desired character. Example: Use of Unicode Escape Sequences package com.tutorialspoint; public class UnicodeCharacterDemo { public static void main (String[]args) { //Unicode escape sequence char unicodeChar = ”u0041”; // point for ”A” System.out.println(“Stored Unicode Character: ” + unicodeChar); } } Compile and run above program. This will produce the following result − Output Stored Unicode Character: A In the above code snippet, the Unicode escape sequence ”u0041” represents the character ”A.” The escape sequence is assigned to the char variable unicodeChar, and the stored character is then printed to the console. 2. Storing Unicode Values Directly Alternatively, you can directly store a Unicode character in a char variable by enclosing the character in single quotes. However, this approach may not be feasible for characters that cannot be typed directly using a keyboard or are not visible, such as control characters. Example 1: Assigning Unicode Character to Variable package com.tutorialspoint; public class UnicodeCharacterDemo { public static void main(String[] args) { // Storing Unicode character directly char unicodeChar = ”A”; // Directly storing the character ”A” System.out.println(“Stored Unicode Character: ” + unicodeChar); } } Compile and run above program. This will produce the following result − Output Stored Unicode Character: A In this example, the character ”A” is directly enclosed in single quotes and assigned to the char variable unicodeChar. The stored character is then printed to the console. Example 2: Assigning Unicode Values to Variables package com.tutorialspoint; public class UnicodeCharacterDemo { public static void main(String[] args) { // Storing Unicode characters using escape sequences char letterA = ”u0041”; char letterSigma = ”u03A3”; char copyrightSymbol = ”u00A9”; // Storing Unicode characters directly char letterZ = ”Z”; char letterOmega = ”Ω”; char registeredSymbol = ”®”; // Printing the stored Unicode characters System.out.println(“Stored Unicode Characters using Escape Sequences:”); System.out.println(“Letter A: ” + letterA); System.out.println(“Greek Capital Letter Sigma: ” + letterSigma); System.out.println(“Copyright Symbol: ” + copyrightSymbol); System.out.println(“nStored Unicode Characters Directly:”); System.out.println(“Letter Z: ” + letterZ); System.out.println(“Greek Capital Letter Omega: ” + letterOmega); System.out.println(“Registered Symbol: ” + registeredSymbol); } } Compile and run above program. This will produce the following result − Output Stored Unicode Characters using Escape Sequences: Letter A: A Greek Capital Letter Sigma: Σ Copyright Symbol: © Stored Unicode Characters Directly: Letter Z: Z Greek Capital Letter Omega: Ω Registered Symbol: ® Example 3: Assigning Unicode Characters and Values to Variables This example demonstrates how to manipulate the stored Unicode characters. It calculates the difference between the capital letter ”A” and the small letter ”a” and uses that difference to calculate the capital letter ”C.” It then calculates the small letter ”c” by adding 32 to the Unicode code point of the capital letter ”C.” The manipulated Unicode characters are printed to the console. package com.tutorialspoint; public class UnicodeCharacterDemo { public static void main(String[] args) { // Storing Unicode characters using escape sequences char letterA = ”u0041”; char letterSmallA = ”u0061”; // Storing Unicode characters directly char letterB = ”B”; // Manipulating the stored Unicode characters int difference = letterA – letterSmallA; char letterC = (char) (letterB + difference); char letterSmallC = (char) (letterC + 32); // Printing the manipulated Unicode characters System.out.println(“Manipulated Unicode Characters:”); System.out.println(“Difference between A and a: ” + difference); System.out.println(“Calculated Letter C: ” + letterC); System.out.println(“Calculated Letter c: ” + letterSmallC); } } Compile and run above program. This will produce the following result − Output Manipulated Unicode Characters: Difference between A and a: -32 Calculated Letter C: ” Calculated Letter c: B Conclusion In Java, you can store Unicode characters using character literals by employing either Unicode escape sequences or directly enclosing the characters in single quotes. Both approaches have their advantages and limitations. Escape sequences provide a consistent way to represent any Unicode character in the source code, while directly storing characters is more convenient when dealing with characters that can be easily typed or displayed. This article has provided an algorithm to store Unicode characters in Java, discussed two different approaches for

Java – Basic Syntax

Java – Basic Syntax ”; Previous Next When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other”s methods. Let us now briefly look into what do class, object, methods, and instance variables mean. Object − Objects have states and behaviors. Example: A dog has states – color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class. Class − A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports. Methods − A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables − Each object has its unique set of instance variables. An object”s state is created by the values assigned to these instance variables. First Java Program Let us look at a simple code that will print the words Hello World. Example public class MyFirstJavaProgram { /* This is my first java program. * This will print ”Hello World” as the output */ public static void main(String []args) { System.out.println(“Hello World”); // prints Hello World } } Let”s look at how to save the file, compile, and run the program. Please follow the subsequent steps − Open notepad and add the code as above. Save the file as: MyFirstJavaProgram.java. Open a command prompt window and go to the directory where you saved the class. Assume it”s C:. Type ”javac MyFirstJavaProgram.java” and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption : The path variable is set). Now, type ” java MyFirstJavaProgram ” to run your program. You will be able to see ” Hello World ” printed on the window. Output C:> javac MyFirstJavaProgram.java C:> java MyFirstJavaProgram Hello World Basic Syntax About Java programs, it is very important to keep in mind the following points. Case Sensitivity − Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. Class Names − For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word”s first letter should be in Upper Case. Example − class MyFirstJavaClass Method Names − All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word”s first letter should be in Upper Case. Example − public void myMethodName() Program File Name − Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append ”.java” to the end of the name (if the file name and the class name do not match, your program will not compile). But please make a note that in case you do not have a public class present in the file then file name can be different than class name. It is also not mandatory to have a public class in the file. Example − Assume ”MyFirstJavaProgram” is the class name. Then the file should be saved as ”MyFirstJavaProgram.java” public static void main(String args[]) − Java program processing starts from the main() method which is a mandatory part of every Java program. Java Identifiers All Java components require names. Names used for classes, variables, and methods are called identifiers. In Java, there are several points to remember about identifiers. They are as follows − All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an underscore (_). After the first character, identifiers can have any combination of characters. A key word cannot be used as an identifier. Most importantly, identifiers are case sensitive. Examples of legal identifiers: age, $salary, _value, __1_value. Examples of illegal identifiers: 123abc, -salary. Java Modifiers Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers − Access Modifiers − default, public , protected, private Non-access Modifiers − final, abstract, strictfp We will be looking into more details about modifiers in the next section. Java Variables Following are the types of variables in Java − Local Variables Class Variables (Static Variables) Instance Variables (Non-static Variables) Java Arrays Arrays are objects that store multiple variables of the same type. However, an array itself is an object on the heap. We will look into how to declare, construct, and initialize in the upcoming chapters. Java Enums Enums were introduced in Java 5.0. Enums restrict a variable to have one of only a few predefined values. The values in this enumerated list are called enums. With the use of enums it is possible to reduce the number of bugs in your code. For example, if we consider an application for a fresh juice shop, it would be possible to restrict the glass size to small, medium, and large. This would make sure that it would not allow anyone to order any size other than small, medium, or large. Example class FreshJuice { enum FreshJuiceSize{ SMALL, MEDIUM, LARGE } FreshJuiceSize size; } public class FreshJuiceTest { public static void main(String args[]) { FreshJuice juice = new FreshJuice(); juice.size = FreshJuice.FreshJuiceSize.MEDIUM ; System.out.println(“Size: ” + juice.size); } } Output The above example will produce the following result − Size: MEDIUM Note − Enums can be declared as their own or inside a class. Methods, variables, constructors can be defined inside enums as well. Java Keywords The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. Sr.No Reserved Words & Description 1 abstract As per dictionary, abstraction is the quality of dealing with ideas rather than