Java – Object & Classes

Java – Classes and Objects ”; Previous Next Java is an Object-Oriented programming language. In Java, the classes and objects are the basic and important features of object-oriented programming system, Java supports the following fundamental OOPs concepts – Classes Objects Inheritance Polymorphism Encapsulation Abstraction Instance Method Message Passing In this tutorial, we will learn about Java Classes and Objects, the creation of the classes and objects, accessing class methods, etc. What are Java Classes? A class is a blueprint from which individual objects are created (or, we can say a class is a data type of an object type). In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and manipulated through the objects. For example, if you want to create a class for students. In that case, “Student” will be a class, and student records (like student1, student2, etc) will be objects. We can also consider that class is a factory (user-defined blueprint) to produce objects. Properties of Java Classes A class does not take any byte of memory. A class is just like a real-world entity, but it is not a real-world entity. It”s a blueprint where we specify the functionalities. A class contains mainly two things: Methods and Data Members. A class can also be a nested class. Classes follow all of the rules of OOPs such as inheritance, encapsulation, abstraction, etc. Types of Class Variables A class can contain any of the following variable types. Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class. Class variables − Class variables are variables declared within a class, outside any method, with the static keyword. Creating (Declaring) a Java Class To create (declare) a class, you need to use access modifiers followed by class keyword and class_name. Syntax to create a Java class Use the below syntax to create (declare) class in Java: access_modifier class class_name{ data members; constructors; methods; …; } Example of a Java Class In this example, we are creating a class “Dog“. Where, the class attributes are breed, age, and color. The class methods are setBreed(), setAge(), setColor(), and printDetails(). // Creating a Java class class Dog { // Declaring and initializing the attributes String breed; int age; String color; // methods to set breed, age, and color of the dog public void setBreed(String breed) { this.breed = breed; } public void setAge(int age) { this.age = age; } public void setColor(String color) { this.color = color; } // method to print all three values public void printDetails() { System.out.println(“Dog detials:”); System.out.println(this.breed); System.out.println(this.age); System.out.println(this.color); } } What are Java Objects? An object is a variable of the type class, it is a basic component of an object-oriented programming system. A class has the methods and data members (attributes), these methods and data members are accessed through an object. Thus, an object is an instance of a class. If we consider the real world, we can find many objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior. If we consider a dog, then its state is – name, breed, and color, and the behavior is – barking, wagging the tail, and running. If you compare the software object with a real-world object, they have very similar characteristics. Software objects also have a state and a behavior. A software object”s state is stored in fields and behavior is shown via methods. So, in software development, methods operate on the internal state of an object, and the object-to-object communication is done via methods. Creating (Declaring) a Java Object As mentioned previously, a class provides the blueprints for objects. So basically, an object is created from a class. In Java, the new keyword is used to create new objects. There are three steps when creating an object from a class − Declaration − A variable declaration with a variable name with an object type. Instantiation − The ”new” keyword is used to create the object. Initialization − The ”new” keyword is followed by a call to a constructor. This call initializes the new object. Syntax to Create a Java Object Consider the below syntax to create an object of the class in Java: Class_name object_name = new Class_name([parameters]); Note: parameters are optional and can be used while you”re using constructors in the class. Example to Create a Java Object In this example, we are creating an object named obj of Dog class and accessing its methods. // Creating a Java class class Dog { // Declaring and initializing the attributes String breed; int age; String color; // methods to set breed, age, and color of the dog public void setBreed(String breed) { this.breed = breed; } public void setAge(int age) { this.age = age; } public void setColor(String color) { this.color = color; } // method to print all three values public void printDetails() { System.out.println(“Dog detials:”); System.out.println(this.breed); System.out.println(this.age); System.out.println(this.color); } } public class Main { public static void main(String[] args) { // Creating an object of the class Dog Dog obj = new Dog(); // setting the attributes obj.setBreed(“Golden Retriever”); obj.setAge(2); obj.setColor(“Golden”); // Printing values obj.printDetails(); } } Output Dog detials: Golden Retriever 2 Golden Accessing Instance Variables and Methods Instance variables and methods are accessed via created objects. To access an instance variable, following is the fully qualified path − /* First create an object */ ObjectReference = new Constructor(); /* Now call a variable as follows */ ObjectReference.variableName; /* Now you can call a class method as follows */ ObjectReference.MethodName(); Example In this example, We”ve created a class named Puppy.

Java – OOPs Concepts

Java – OOPs (Object-Oriented Programming) Concepts ”; Previous Next OOPs (Object-Oriented Programming System) Object means a real-world entity such as a mobile, book, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts. In this tutorial, we will learn about the concepts of Java (OOPs) object-oriented programming systems. Java OOPs (Object-Oriented Programming) Concepts Object Class Inheritance Polymorphism Abstraction Encapsulation 1. Object In object-oriented programming, an object is an entity that has two characteristics (states and behavior). Some of the real-world objects are book, mobile, table, computer, etc. An object is a variable of the type class, it is a basic component of an object-oriented programming system. A class has the methods and data members (attributes), these methods and data members are accessed through an object. Thus, an object is an instance of a class. 2. Class In object-oriented programming, a class is a blueprint from which individual objects are created (or, we can say a class is a data type of an object type). In Java, everything is related to classes and objects. Each class has its methods and attributes that can be accessed and manipulated through the objects. 3. Inheritance In object-oriented programming, inheritance is a process by which we can reuse the functionalities of existing classes to new classes. In the concept of inheritance, there are two terms base (parent) class and derived (child) class. When a class is inherited from another class (base class), it (derived class) obtains all the properties and behaviors of the base class. 4. Polymorphism The term “polymorphism” means “many forms”. In object-oriented programming, polymorphism is useful when you want to create multiple forms with the same name of a single entity. To implement polymorphism in Java, we use two concepts method overloading and method overriding. The method overloading is performed in the same class where we have multiple methods with the same name but different parameters, whereas, the method overriding is performed by using the inheritance where we can have multiple methods with the same name in parent and child classes. 5. Abstraction In object-oriented programming, an abstraction is a technique of hiding internal details and showing functionalities. The abstract classes and interfaces are used to achieve abstraction in Java. The real-world example of an abstraction is a Car, the internal details such as the engine, process of starting a car, process of shifting gears, etc. are hidden from the user, and features such as the start button, gears, display, break, etc are given to the user. When we perform any action on these features, the internal process works. 6. Encapsulation In an object-oriented approach, encapsulation is a process of binding the data members (attributes) and methods together. The encapsulation restricts direct access to important data. The best example of the encapsulation concept is making a class where the data members are private and methods are public to access through an object. In this case, only methods can access those private data. Advantages of Java OOPs The following are the advantages of using the OOPs in Java: The implementations of OOPs concepts are easier. The execution of the OOPs is faster than procedural-oriented programming. OOPs provide code reusability so that a programmer can reuse an existing code. OOPs help us to keep the important data hidden. Print Page Previous Next Advertisements ”;

Java – Class Methods

Java – Class Methods ”; Previous Next Java Class Methods The class methods are methods that are declared within a class. They perform specific operations and can access, modify the class attributes. Creating (Declaring) Java Class Methods Class methods declaration is similar to the user-defined methods declaration except that class methods are declared within a class. The class methods are declared by specifying the access modifier followed by the return type, method_name, and parameters list. Syntax Use the below syntax to declare a Java class method: public class class_name { modifier returnType nameOfMethod(Parameter List) { // method body } } The syntax shown above includes − modifier − It defines the access type of the method and it is optional to use. returnType − The returns data type of the class method. nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list. Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters. method body − The method body defines what the method does with the statements. Example Here is the source code of the above defined method called minimum(). This method takes two parameters n1 and n2 and returns the minimum between the two − class Util { /** the snippet returns the minimum between two numbers */ public int minimum(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } } Accessing Java Class Methods To access a class method (public class method), you need to create an object first, then by using the object you can access the class method (with the help of dot (.) operator). Syntax Use the below syntax to access a Java public class method: object_name.method_name([parameters]); Example Following is the example to demonstrate how to define class method and how to access it. Here, We”ve created an object of Util class and call its minimum() method to get minimum value of given two numbers − package com.tutorialspoint; class Util { public int minimum(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } } public class Tester { public static void main(String[] args) { int a = 11; int b = 6; Util util = new Util(); int c = util.minimum(a, b); System.out.println(“Minimum Value = ” + c); } } Output Minimum value = 6 this Keyword in Java Class Methods this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods. Note − The keyword this is used only within instance methods or constructors In general, the keyword this is used to − Differentiate the instance variables from local variables if they have same names, within a constructor or a method. class Student { int age; Student(int age) { this.age = age; } } Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation. class Student { int age Student() { this(20); } Student(int age) { this.age = age; } } Example: Using this Keyword in Java Class Methods Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, Tester.java. package com.tutorialspoint; public class Tester { // Instance variable num int num = 10; Tester() { System.out.println(“This is an example program on keyword this”); } Tester(int num) { // Invoking the default constructor this(); // Assigning the local variable num to the instance variable num this.num = num; } public void greet() { System.out.println(“Hi Welcome to Tutorialspoint”); } public void print() { // Local variable num int num = 20; // Printing the local variable System.out.println(“value of local variable num is : “+num); // Printing the instance variable System.out.println(“value of instance variable num is : “+this.num); // Invoking the greet method of a class this.greet(); } public static void main(String[] args) { // Instantiating the class Tester obj1 = new Tester(); // Invoking the print method obj1.print(); // Passing a new value to the num variable through parametrized constructor Tester obj2 = new Tester(30); // Invoking the print method again obj2.print(); } } Output This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 10 Hi Welcome to Tutorialspoint This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 30 Hi Welcome to Tutorialspoint Public Vs. Static Class Methods There are two types of class methods public and static class method. The public class methods are accessed through the objects whereas, the static class methods are accessed are accesses without an object. You can directly access the static methods. Example The following example demonstrates the difference between public and static class methods: public class Main { // Creating a static method static void fun1() { System.out.println(“fun1: This is a static method.”); } // Creating a public method public void fun2() { System.out.println(“fun2: This is a public method.”); } // The main() method public static void main(String[] args) { // Accessing static method through the class fun1(); // Creating an object of the Main class Main obj = new Main(); // Accessing public method through the object obj.fun2(); } } Output fun1: This is a static method. fun2: This is a public method. The finalize( ) Method It is possible to define a method that will be called just before an object”s final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

Java – Comments

Java Comments ”; Previous Next Java Comments Java comments are text notes written in the code to provide an explanation about the source code. The comments can be used to explain the logic or for documentation purposes. The compiler does not compile the comments. In Java, comments are very similar to C and C++. In Java, there are three types of comments: Single-line comments Multiline comments Documentation comments Let”s discuss each type of comment in detail. 1. Single Line Comment The single-line comment is used to add a comment on only one line and can be written by using the two forward slashes (//). These comments are the most used commenting way. The single line comments are the most used commenting way to explain the purpose (or to add a text note) of the line. Syntax Consider the below syntax to write a single line comment in Java: // comment Example 1: Java Single Line Comment // if divisor is 0 throw an exception if (divisor == 0) { throw new IllegalArgumentException(“divisor cannot be zero”); } Example 2: Java Single Line Comment Following code shows the usage of single line comments in a simple program. We”ve added comments to code lines to explain their purpose. package com.tutorialspoint; public class MyFirstJavaProgram { public static void main(String[] args) { MyFirstJavaProgram program = new MyFirstJavaProgram(); double result = program.divide(100, 10); System.out.println(result); } private double divide(int dividend, int divisor) throws IllegalArgumentException { // if divisor is 0 throw an exception if (divisor == 0) { throw new IllegalArgumentException(“divisor cannot be zero”); } return (double) dividend / divisor; // returns the result of the division as double } } Output Compile and run MyFirstJavaProgram. This will produce the following result − 10.0 2. Multiline Comment The multiline (or, multiple-line) comments start with a forward slash followed by an asterisk (/*) and end with an asterisk followed by a forward slash (*/) and they are used to add comment on multiple lines. The multiline comments are very useful when we want to put a long comment spreading across multiple lines or to comment out the complete code. Syntax: Consider the below syntax to write multiline comment in Java: /* Comment (line 1) Comment (line 2) … */ Example 1: Java Multiline Comment /* This is an example of multi line comment. */ /* if (dividend == 0) { throw new IllegalArgumentException(“dividend cannot be zero”); } */ Example 2: Java Multiline Comment Following code shows the usage of multiple comments in a simple program. We”ve commented out extra code from a method using Multiline comments. package com.tutorialspoint; public class MyFirstJavaProgram { public static void main(String[] args) { MyFirstJavaProgram program = new MyFirstJavaProgram(); double result = program.divide(100, 10); System.out.println(result); } private double divide(int dividend, int divisor) throws IllegalArgumentException { if (divisor == 0) { throw new IllegalArgumentException(“divisor cannot be zero”); } /* if (dividend == 0) { throw new IllegalArgumentException(“dividend cannot be zero”); } */ return (double) dividend / divisor; } } Output Compile and run MyFirstJavaProgram. This will produce the following result − 10.0 3. Documentation Comment The documentation comments are used for writing the documentation of the source code. The documentation comments start with a forward slash followed by the two asterisks (/**), end with an asterisk followed by a backward slash (*/), and all lines between the start and end must start with an asterisk (*). The documentation comments are understood by the Javadoc tool and can be used to create HTML-based documentation. Syntax Consider the below syntax to write documentation comment in Java: /** * line 1 * line 2 … */ Example 1: Java Documentation Comment /** * This is a documentation comment. * This is my first Java program. * This will print ”Hello World” as the output * This is an example of multi-line comments. */ public class MyFirstJavaProgram {} The above commenting style is known as documentation comments. It is used by Javadoc tool while creating the documentation for the program code. We can give details of arguments, exception and return type as well using following annotation in documentation comments. /** * @param dividend * @param divisor * @return quotient * @throws IllegalArgumentException if divisor is zero */ private double divide(int dividend, int divisor) throws IllegalArgumentException { } Example 2: Java Documentation Comment Following code shows the usage of documentation comments in a simple program. We”ve defined a comments on the class declaration to give details of the class. In case of method, we”re adding details of parameters, return value and exception raised in documentation block of the method comments section. package com.tutorialspoint; /** * This is a documentation comment. * This is my first Java program. * This is an example of multi-line comments. * We”re printing result of divison of two numbers in this program */ public class MyFirstJavaProgram { public static void main(String[] args) { MyFirstJavaProgram program = new MyFirstJavaProgram(); double result = program.divide(100, 10); System.out.println(result); } /** * @param dividend * @param divisor * @return quotient * @throws IllegalArgumentException if divisor is zero */ private double divide(int dividend, int divisor) throws IllegalArgumentException { if (divisor == 0) { throw new IllegalArgumentException(“divisor cannot be zero”); } return (double) dividend / divisor; } } Output Compile and run MyFirstJavaProgram. This will produce the following result − 10.0 Print Page Previous Next Advertisements ”;

Java – JDK vs JRE vs JVM

Difference Between JDK, JRE, and JVM ”; Previous Next All three JDK, JRE and JVM are interdependent. JDK is Java Development Kit primarily meant for Developers to develop Java based applications. JRE is Java Runtime Environment where Java program runs. JDK carries JRE as an integral part of it. JRE can be installed seperately as well on systems where no developement is to be done and we only need to run the Java based application or a java program is to be executed. The JVM is a specification, and can have different implementations, as long as they adhere to the specs. The specs can be found in the below link − https://docs.oracle.com. JRE is an implementation of the JVM. What is JDK? JDK is an abbreviation for Java Development Kit which includes all the tools, executables, and binaries required to compile, debug, and execute a Java Program.JDK is platform dependent i.e. there are separate installers for Windows, Mac, and Unix systems. JDK includes both JVM and JRE and is entirely responsible for code execution. It is the version of JDK that represents a version of Java. What is JRE? JRE is a Java Runtime Environment which is the implementation of JVM i.e. the specifications that are defined in JVM are implemented and create a corresponding environment for the execution of code. JRE comprises mainly Java binaries and other classes to execute the program like JVM which physically exists. Along with Java binaries JRE also consists of various technologies of deployment, user interfaces to interact with code executed, some base libraries for different functionalities, and language and util-based libraries. What is JVM? JVM is the abbreviation for Java Virtual Machine which is a specification that provides a runtime environment in which Java byte code can be executed i.e. it is something that is abstract and its implementation is independent of choosing the algorithm and has been provided by Sun and other companies. It is JVM which is responsible for converting Byte code to machine-specific code. It can also run those programs which are written in other languages and compiled to Java bytecode. The JVM performs the mentioned tasks: Loads code, Verifies code, Executes code, and Provides runtime environment. Difference between JDK, JRE, and JVM Following are the important differences between JDK, JRE, and JVM − Sr. No. Key JDK JRE JVM 1 Definition JDK (Java Development Kit) is a software development kit to develop applications in Java. In addition to JRE, JDK also contains number of development tools (compilers, JavaDoc, Java Debugger etc.). JRE (Java Runtime Environment) is the implementation of JVM and is defined as a software package that provides Java class libraries, along with Java Virtual Machine (JVM), and other components to run applications written in Java programming. JVM (Java Virtual Machine) is an abstract machine that is platform-dependent and has three notions as a specification, a document that describes requirement of JVM implementation, implementation, a computer program that meets JVM requirements, and instance, an implementation that executes Java byte code provides a runtime environment for executing Java byte code. 2 Prime functionality JDK is primarily used for code execution and has prime functionality of development. On other hand JRE is majorly responsible for creating environment for code execution. JVM on other hand specifies all the implementations and responsible to provide these implementations to JRE. 3 Platform Independence JDK is platform dependent i.e for different platforms different JDK required. Like of JDK JRE is also platform dependent. JVM is platform independent. 4 Tools As JDK is responsible for prime development so it contains tools for developing, debugging and monitoring java application. On other hand JRE does not contain tools such as compiler or debugger etc. Rather it contains class libraries and other supporting files that JVM requires to run the program. JVM does not include software development tools. 5 Implementation JDK = Java Runtime Environment (JRE) + Development tools JRE = Java Virtual Machine (JVM) + Libraries to run the application JVM = Only Runtime environment for executing the Java byte code. Print Page Previous Next Advertisements ”;

Java – Variable Types

Java – Variable Types ”; Previous Next What is a Java Variable? A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable”s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable. Variable Declaration and Initialization You must declare all variables before they can be used. Following is the basic form of a variable declaration − data type variable [ = value][, variable [ = value] …] ; Here data type is one of Java”s data types and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list. Example of Valid Variables Declarations and Initializations Following are valid examples of variable declaration and initialization in Java − int a, b, c; // Declares three ints, a, b, and c. int a = 10, b = 10; // Example of initialization byte B = 22; // initializes a byte type variable B. double pi = 3.14159; // declares and assigns a value of PI. char a = ”a”; // the char variable a iis initialized with value ”a” Java Variables Types The following are the three types of Java variables: Local variables Instance variables Class/Static variables 1. Java Local Variables Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block. Access modifiers cannot be used for local variables. Local variables are visible only within the declared method, constructor, or block. Local variables are implemented at stack level internally. There is no default value for local variables, so local variables should be declared and an initial value should be assigned before the first use. Example 1: Variable”s local scope with initialization Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to only this method. public class Test { public void pupAge() { int age = 0; age = age + 7; System.out.println(“Puppy age is : ” + age); } public static void main(String args[]) { Test test = new Test(); test.pupAge(); } } Output Puppy age is: 7 Example 2: Variable”s local scope without initialization Following example uses age without initializing it, so it would give an error at the time of compilation. public class Test { public void pupAge() { int age; age = age + 7; System.out.println(“Puppy age is : ” + age); } public static void main(String args[]) { Test test = new Test(); test.pupAge(); } } Output Test.java:4:variable number might not have been initialized age = age + 7; ^ 1 error 2. Java Instance Variables Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables are created when an object is created with the use of the keyword ”new” and destroyed when the object is destroyed. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object”s state that must be present throughout the class. Instance variables can be declared in class level before or after use. Access modifiers can be given for instance variables. The instance variables are visible for all methods, constructors and block in the class. Normally, it is recommended to make these variables private (access level). However, visibility for subclasses can be given for these variables with the use of access modifiers. Instance variables have default values. For numbers, the default value is 0, for Booleans it is false, and for object references it is null. Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name. ObjectReference.VariableName. Example of Java Instance Variables import java.io.*; public class Employee { // this instance variable is visible for any child class. public String name; // salary variable is visible in Employee class only. private double salary; // The name variable is assigned in the constructor. public Employee (String empName) { name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal) { salary = empSal; } // This method prints the employee details. public void printEmp() { System.out.println(“name : ” + name ); System.out.println(“salary :” + salary); } public static void main(String args[]) { Employee empOne = new Employee(“Ransika”); empOne.setSalary(1000); empOne.printEmp(); } } Output name : Ransika salary :1000.0 3. Java Class/Static Variables Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it. Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value. Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants. Static variables are created when the program starts and destroyed when the program stops. Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class. Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special

Java – Decision Making

Java – Decision Making ”; Previous Next Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Following is the general form of a typical decision making structure found in most of the programming languages − Java programming language provides following types of decision making statements. Click the following links to check their detail. Sr.No. Statement & Description 1 if statement An if statement consists of a boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the boolean expression is false. 3 nested if statement You can use one if or else if statement inside another if or else if statement(s). 4 switch statement A switch statement allows a variable to be tested for equality against a list of values. The ? : Operator We have covered conditional operator ? : in the previous chapter which can be used to replace if…else statements. It has the following general form − Exp1 ? Exp2 : Exp3; Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon. To determine the value of the whole expression, initially exp1 is evaluated. If the value of exp1 is true, then the value of Exp2 will be the value of the whole expression. If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression. Example In this example, we”re creating two variables a and b and using ternary operator we”ve decided the values of b and printed it. public class Test { public static void main(String args[]) { int a, b; a = 10; b = (a == 1) ? 20: 30; System.out.println( “Value of b is : ” + b ); b = (a == 10) ? 20: 30; System.out.println( “Value of b is : ” + b ); } } Output Value of b is : 30 Value of b is : 20 What is Next? In the next chapter, we will discuss about Number class (in the java.lang package) and its subclasses in Java Language. We will be looking into some of the situations where you will use instantiations of these classes rather than the primitive data types, as well as classes such as formatting, mathematical functions that you need to know about when working with Numbers. Print Page Previous Next Advertisements ”;

Java – History

Java – History ”; Previous Next History of Java Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems” Java platform (Java 1.0 [J2SE]). History of even naming of the Java is very interesting. It went under many names. Java Name History GreenTalk James Gosling was leading a team named as ”Green” team. Target of this team was to create a new project which can. Initially C++ was the original choice to develop the project. James Gosling wanted to enhance C++ to achieve the target but due to high memory usage, that idea was rejected and team started with a new language initially named as GreenTalk. The file extension used as .gt. Later this language was termed as Oak and finally to Java. Oak James Gosling renamed language to Oak. There was an Oak tree in front of his office. James Gosling used this name as Oak represents solidarity and Oak tree is the national tree of multiple countries like USA, France, Romania etc. But Oak technologies already had Oak as a trademark and James team had to brainstrom another title for the language. Finally Java Team put multiple names like DNA, Silk, Ruby and Java. Java was finalized by the team. James Gosling tabled Java title based on type of espresso coffee bean. Java is an island in Indonesia where new coffee was discovered termed as Java coffee. As per James Gosling, Java was among the top choice along with Silk. Finally Java was selected as it was quite unique and represented the essence of being dynamic,revolutionary and fun to say. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java”s core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright. The latest release of the Java Standard Edition is Java SE 21. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. Java Versions History Over the period of nearly 30 years, Java has seen many minor and major versions. Following is a brief explaination of versions of java till date. Sr.No. Version Date Description 1 JDK Beta 1995 Initial Draft version 2 JDK 1.0 23 Jan 1996 A stable variant JDK 1.0.2 was termed as JDK 1 3 JDK 1.1 19 Feb 1997 Major features like JavaBeans, RMI, JDBC, inner classes were added in this release. 4 JDK 1.2 8 Dec 1998 Swing, JIT Compiler, Java Modules, Collections were introduced to JAVA and this release was a great success. 5 JDK 1.3 8 May 2000 HotSpot JVM, JNDI, JPDA, JavaSound and support for Synthetic proxy classes were added. 6 JDK 1.4 6 Feb 2002 Image I/O API to create/read JPEG/PNG image were added. Integrated XML parser and XSLT processor (JAXP) and Preferences API were other important updates. 7 JDK 1.5 or J2SE 5 30 Sep 2004 Various new features were added to the language like foreach, var-args, generics etc. 8 JAVA SE 6 11 Dec 2006 1. notation was dropped to SE and upgrades done to JAXB 2.0, JSR 269 support and JDBC 4.0 support added. 9 JAVA SE 7 7 Jul 2011 Support for dynamic languages added to JVM. Another enhancements included string in switch case, compressed 64 bit pointers etc. 10 JAVA SE 8 18 Mar 2014 Support for functional programming added. Lambda expressions,streams, default methods, new date-time APIs introduced. 11 JAVA SE 9 21 Sep 2017 Module system introduced which can be applied to JVM platform. 12 JAVA SE 10 20 Mar 2018 Unicode language-tag extensions added. Root certificates, threadlocal handshakes, support for heap allocation on alternate memory devices etc were introduced. 13 JAVA SE 11 5 Sep 2018 Dynamic class-file constants,Epsilon a no-op garbage collector, local-variable support in lambda parameters, Low-overhead heap profiling support added. 14 JAVA SE 12 19 Mar 2019 Experimental Garbage Collector,Shenandoah: A Low-Pause-Time Garbage Collector, Microbenchmark Suite, JVM Constants API added. 15 JAVA SE 13 17 Sep 2019 Feature added – Text Blocks (Multiline strings), Enhanced Thread-local handshakes. 16 JAVA SE 14 17 Mar 2020 Feature added – Records, a new class type for modelling, Pattern Matching for instanceof, Intuitive NullPointerException handling. 17 JAVA SE 15 15 Sep 2020 Feature added – Sealed Classes, Hidden Classes, Foreign Function and Memory API (Incubator). 18 JAVA SE 16 16 Mar 2021 Feature added as preview – Records, Pattern Matching for switch, Unix Domain Socket Channel (Incubator) etc. 19 JAVA SE 17 14 Sep 2021 Feature added as finalized – Sealed Classes, Pattern Matching for instanceof, Strong encapsulation of JDK internals by default. New macOS rendering pipeline etc. 20 JAVA SE 18 22 Mar 2022 Feature added – UTF-8 by Default, Code Snippets in Java API Documentation, Vector API (Third incubator), Foreign Function, Memory API (Second Incubator) etc. 21 JAVA SE 19 20 Sep 2022 Feature added – Record pattern, Vector API (Fourth incubator), Structured Concurrency (Incubator) etc. 22 JAVA SE 20 21 Mar 2023 Feature added – Scoped Values (Incubator), Record Patterns (Second Preview), Pattern Matching for switch (Fourth Preview),Foreign Function & Memory API (Second Preview) etc. 22 JAVA SE 21 19 Sep 2023 Feature added – String Templates (Preview), Sequenced Collections, Generational ZGC, Record Patterns, Pattern Matching for switch etc. Print Page Previous Next Advertisements ”;

Java – Overview

Java – Overview ”; Previous Next Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems” Java platform (Java 1.0 [J2SE]). The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere. Java is − Object Oriented − In Java, everything is an Object. Java can be easily extended since it is based on the Object model. Platform Independent − Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. Simple − Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. Secure − With Java”s secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Architecture-neutral − Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. Portable − Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Robust − Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Multithreaded − With Java”s multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. Interpreted − Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. High Performance − With the use of Just-In-Time compilers, Java enables high performance. Distributed − Java is designed for the distributed environment of the internet. Dynamic − Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time. Hello World using Java Programming Just to give you a little excitement about Java programming, I”m going to give you a small conventional C Programming Hello World program, You can try it using Demo link. 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 } } History of Java James Gosling initiated Java language project in June 1991 for use in one of his many set-top box projects. The language, initially called ”Oak” after an oak tree that stood outside Gosling”s office, also went by the name ”Green” and ended up later being renamed as Java, from a list of random words. Sun released the first public implementation as Java 1.0 in 1995. It promised Write Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms. On 13 November, 2006, Sun released much of Java as free and open source software under the terms of the GNU General Public License (GPL). On 8 May, 2007, Sun finished the process, making all of Java”s core code free and open-source, aside from a small portion of code to which Sun did not hold the copyright. Tools You Will Need For performing the examples discussed in this tutorial, you will need a Pentium 200-MHz computer with a minimum of 64 MB of RAM (128 MB of RAM recommended). You will also need the following softwares − Linux 7.1 or Windows xp/7/8 operating system Java JDK 8 Microsoft Notepad or any other text editor This tutorial will provide the necessary skills to create GUI, networking, and web applications using Java. What is Next? The next chapter will guide you to how you can obtain Java and its documentation. Finally, it instructs you on how to install Java and prepare an environment to develop Java applications. Print Page Previous Next Advertisements ”;

Java – Features

Java – Features ”; Previous Next Java programming language was initially developed to work on embedded systems, settop boxes, television. So by requirements, it was initially designed to work on varied platforms. Over the period of multiple years, Java evolved to become one of the most popular language used to develop internet based applications. Java is a feature rich language and with every new version, it is continously evolving. It is widely used across billions of devices. Following are the main features of the Java language – Object Oriented Platform Independent Simple Secure Architecture-neutral Portable Robust Multithreaded Interpreted High Performance Distributed Dynamic Object Oriented In Java, everything is an Object. Java can be easily extended since it is based on the Object model. As a language that has the Object-Oriented feature, Java supports the following fundamental concepts of OOPs − Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method Message Passing Platform Independent Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Java Virtual Machine (JVM) on whichever platform it is being run on. Java is designed in Write Once, Run Anywhere (WORA) way. Code written in Java is not directly dependent on the type of machine it is running. A code is Java is compiled in ByteCode which is platform independent. Java Virtual Machine, JVM can understand the byte code. Java provides platform specific JVMs. It is the responsibility of platform specific JVM to interpret the byte code correctly thus developers are free to write code without worrying about platforms like windows, linux, unix, Mac etc. This feature makes Java a platform neutral language. As byte code can be distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. It makes java code highly portable and useful for application running on multiple platforms. Simple Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master. Java is very easy to learn. It inherits many features from C, C++ and removes complex features like pointers, operator overloading, multiple inheritance, explicit memory allocation etc. It provides automatic garbage collection. With a rich set of libraries with thousands of useful functions, Java makes developers life easy. Secure With Java”s secure feature it enables to develop virus-free, tamper-free systems. Authentication techniques are based on public-key encryption. Java is by design highly secure as it is not asking developers to interact with underlying system memory or operation system. Bytecode is secure and several security flaws like buffer overflow, memory leak are very rare. Java exception handling mechanism allows developers to handle almost all type of error/exceptions which can happen during program execution. Automatic garbage collection helps in maintaining the system memory space utilization in check. Architecture-neutral Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. With advancement in processor architectures or machine specific processors, java code remains independent of any specific requirement of a processor. As java is an open standard, even a specific JVM can be prepared for a custom architecture. As in today”s time, we”ve JVM available for almost all popular platforms, architectures, java code is completely independent. For example, a java program created in Windows machine can run on linux machine without any code modification. Portable Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. Due to this portability, java was an instant hit since inception. It was particulary useful for internet based application where platforms varied from place to place and same code base can be used across multiple platform. So collaboration between developers was easy across multiple locations. Robust Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. Automatic garbage collection, strong memory management, no pointers, no direct access to system memory, exception handling, error handling are some of the key features which makes Java a Robust, strong language to rely on. Multithreaded With Java”s multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. 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. Multithreading 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. Interpreted Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. JVM sits in between the javac compiler and the underlying hardware, the javac (or any other compiler) compiler compiles Java code in the Bytecode, which is understood by a platform specific JVM. The JVM then compiles the Bytecode in binary using JIT (Just-in-time) compilation, as the code executes. High Performance With the use of Just-In-Time compilers, Java enables high performance. JVM uses JIT compiler to improves