<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[OOPS oriented Java Programming Language - Medium]]></title>
        <description><![CDATA[To learn java programming language - Medium]]></description>
        <link>https://medium.com/oops-oriented-java-programming-language?source=rss----55d8364a591a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>OOPS oriented Java Programming Language - Medium</title>
            <link>https://medium.com/oops-oriented-java-programming-language?source=rss----55d8364a591a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 12 Nov 2026 22:27:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/oops-oriented-java-programming-language" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Java Files, Java File Handling, Java Create and Write to a file, Read a File, Delete a File]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-files-java-file-handling-java-create-and-write-to-a-file-read-a-file-delete-a-file-28061205b9aa?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/28061205b9aa</guid>
            <category><![CDATA[create-file]]></category>
            <category><![CDATA[delete-file]]></category>
            <category><![CDATA[java-files]]></category>
            <category><![CDATA[read-and-write-file]]></category>
            <category><![CDATA[java-file-handling]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 10:42:23 GMT</pubDate>
            <atom:updated>2021-03-03T10:42:23.261Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Files</h3><p>File handling is an important part of any application.</p><p>Java has several methods for creating, reading, updating, and deleting files.</p><h3>Java File Handling</h3><p>The File class from the java.io package, allows us to work with files.</p><p>To use the File class, create an object of the class, and specify the filename or directory name:</p><p><strong>Example</strong></p><pre><strong>import java.io.File;  // Import the File class</strong></pre><pre><strong>File myObj = new File(&quot;filename.txt&quot;); // Specify the filename</strong></pre><p><strong>Java Create and Write To Files</strong></p><p><strong>Create a File</strong></p><p>To create a file in Java, you can use the createNewFile() method. This method returns a boolean value: true if the file was successfully created, and false if the file already exists. Note that the method is enclosed in a try...catch block. This is necessary because it throws an IOException if an error occurs (if the file cannot be created for some reason):</p><p><strong>Example</strong></p><pre><strong>import java.io.File;  // Import the File class<br>import java.io.IOException;  // Import the IOException class to handle errors</strong></pre><pre><strong>public class CreateFile {<br>  public static void main(String[] args) {<br>    try {<br>      File myObj = new File(&quot;filename.txt&quot;);<br>      if (myObj.createNewFile()) {<br>        System.out.println(&quot;File created: &quot; + myObj.getName());<br>      } else {<br>        System.out.println(&quot;File already exists.&quot;);<br>      }<br>    } catch (IOException e) {<br>      System.out.println(&quot;An error occurred.&quot;);<br>      e.printStackTrace();<br>    }<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>File created: filename.txt</strong></pre><p>To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the “\&quot; character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt</p><p><strong>Example</strong></p><pre><strong>File myObj = new File(&quot;C:\\Users\\MyName\\filename.txt&quot;);</strong></pre><p><strong>Write To a File</strong></p><p>In the following example, we use the FileWriter class together with its write() method to write some text to the file we created in the example above. Note that when you are done writing to the file, you should close it with the close() method:</p><p><strong>Example</strong></p><pre><strong>import java.io.FileWriter;   // Import the FileWriter class<br>import java.io.IOException;  // Import the IOException class to handle errors</strong></pre><pre><strong>public class WriteToFile {<br>  public static void main(String[] args) {<br>    try {<br>      FileWriter myWriter = new FileWriter(&quot;filename.txt&quot;);<br>      myWriter.write(&quot;Files in Java might be tricky, but it is fun enough!&quot;);<br>      myWriter.close();<br>      System.out.println(&quot;Successfully wrote to the file.&quot;);<br>    } catch (IOException e) {<br>      System.out.println(&quot;An error occurred.&quot;);<br>      e.printStackTrace();<br>    }<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>Successfully wrote to the file.</strong></pre><p><strong>Read a File</strong></p><p>In the following example, we use the Scanner class to read the contents of the text file we created.</p><p><strong>Example</strong></p><pre><strong>import java.io.File;  // Import the File class<br>import java.io.FileNotFoundException;  // Import this class to handle errors<br>import java.util.Scanner; // Import the Scanner class to read text files</strong></pre><pre><strong>public class ReadFile {<br>  public static void main(String[] args) {<br>    try {<br>      File myObj = new File(&quot;filename.txt&quot;);<br>      Scanner myReader = new Scanner(myObj);<br>      while (myReader.hasNextLine()) {<br>        String data = myReader.nextLine();<br>        System.out.println(data);<br>      }<br>      myReader.close();<br>    } catch (FileNotFoundException e) {<br>      System.out.println(&quot;An error occurred.&quot;);<br>      e.printStackTrace();<br>    }<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>Files in Java might be tricky, but it is fun enough!</strong></pre><p><strong>Example</strong></p><pre><strong>import java.io.File;  // Import the File class</strong></pre><pre><strong>public class GetFileInfo { <br>  public static void main(String[] args) {<br>    File myObj = new File(&quot;filename.txt&quot;);<br>    if (myObj.exists()) {<br>      System.out.println(&quot;File name: &quot; + myObj.getName());<br>      System.out.println(&quot;Absolute path: &quot; + myObj.getAbsolutePath());<br>      System.out.println(&quot;Writeable: &quot; + myObj.canWrite());<br>      System.out.println(&quot;Readable &quot; + myObj.canRead());<br>      System.out.println(&quot;File size in bytes &quot; + myObj.length());<br>    } else {<br>      System.out.println(&quot;The file does not exist.&quot;);<br>    }<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>File name: filename.txt<br>Absolute path: C:\Users\MyName\filename.txt<br>Writeable: true<br>Readable: true<br>File size in bytes: 0</strong></pre><p><strong>Note:</strong> There are many available classes in the Java API that can be used to read and write files in Java: FileReader, BufferedReader, Files, Scanner, FileInputStream, FileWriter, BufferedWriter, FileOutputStream, etc. Which one to use depends on the Java version you&#39;re working with and whether you need to read bytes or characters, and the size of the file/lines etc.</p><p><strong>Delete a File</strong></p><p>To delete a file in Java, use the delete() method:</p><p><strong>Example</strong></p><pre><strong>import java.io.File;  // Import the File class</strong></pre><pre><strong>public class DeleteFile {<br>  public static void main(String[] args) { <br>    File myObj = new File(&quot;filename.txt&quot;); <br>    if (myObj.delete()) { <br>      System.out.println(&quot;Deleted the file: &quot; + myObj.getName());<br>    } else {<br>      System.out.println(&quot;Failed to delete the file.&quot;);<br>    } <br>  } <br>}</strong></pre><p>The output will be:</p><pre><strong>Deleted the file: filename.txt</strong></pre><p><strong>Delete a Folder</strong></p><p>You can also delete a folder. However, it must be empty:</p><p><strong>Example</strong></p><pre><strong>import java.io.File; </strong></pre><pre><strong>public class DeleteFolder {<br>  public static void main(String[] args) { <br>    File myObj = new File(&quot;C:\\Users\\MyName\\Test&quot;); <br>    if (myObj.delete()) { <br>      System.out.println(&quot;Deleted the folder: &quot; + myObj.getName());<br>    } else {<br>      System.out.println(&quot;Failed to delete the folder.&quot;);<br>    } <br>  } <br>}</strong></pre><p>The output will be:</p><pre><strong>Deleted the folder: Test</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28061205b9aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-files-java-file-handling-java-create-and-write-to-a-file-read-a-file-delete-a-file-28061205b9aa">Java Files, Java File Handling, Java Create and Write to a file, Read a File, Delete a File</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Packages, Access Specifiers, Exception Handling]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/packages-access-specifiers-exception-handling-3d95731556fe?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d95731556fe</guid>
            <category><![CDATA[java-package]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[access-specifiers]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Wed, 03 Mar 2021 10:05:15 GMT</pubDate>
            <atom:updated>2021-03-03T10:05:15.366Z</atom:updated>
            <content:encoded><![CDATA[<p>The package is a group of related classes and interfaces. The main objective is code reusability. Any class once after derived successfully can be accessed by importing the respective package. package can be created with the help of keyword package.</p><p>Syntax:</p><pre><strong>package &lt;pkg_name&gt;<br>class classname{<br>  //Data Members and Methods<br>}</strong></pre><p>Packages are two different types</p><ol><li>Predefined packages</li><li>User defined packages</li></ol><p>The predefined packages are Java and Javax . The package consists of many sub packages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/0*OLBpgB6XdDJiJLwQ.png" /></figure><p>Depending on the requirement of the user the respective package and the sub package will be imported into the user program using the keyword “import”.</p><p>Syntax:</p><pre><strong>import mainpkg.subpkg.classname</strong></pre><p>Incase of the user defined packages, the package definition and its path will be defined by the user.</p><p><strong>Example</strong></p><pre><strong>└── root<br>  └── mypack<br>    └── MyPackageClass.java</strong></pre><p>To create a package, use the package keyword:</p><p><strong>MyPackageClass.java</strong></p><pre><strong>package mypack;<br>class MyPackageClass {<br>  public static void main(String[] args) {<br>    System.out.println(&quot;This is my package!&quot;);<br>  }<br>}</strong></pre><p>Save the file as <strong>MyPackageClass.java</strong>, and compile it:</p><pre><strong>C:\Users\<em>Your Name</em>&gt;javac MyPackageClass.java</strong></pre><p>Then compile the package:</p><pre><strong>C:\Users\<em>Your Name</em>&gt;javac -d . MyPackageClass.java</strong></pre><p>This forces the compiler to create the “mypack” package.</p><p>The -d keyword specifies the destination for where to save the class file. You can use any directory name, like c:/user (windows), or, if you want to keep the package within the same directory, you can use the dot sign &quot;.&quot;, like in the example above.</p><p><strong>Note:</strong> The package name should be written in lower case to avoid conflict with class names.</p><p>When we compiled the package in the example above, a new folder was created, called “mypack”.</p><p>To run the <strong>MyPackageClass.java</strong> file, write the following:</p><p>C:\Users\<em>Your Name</em>&gt;java mypack.MyPackageClass</p><p>The output will be:</p><pre><strong>This is my package!</strong></pre><h3>Access Specifiers and their accessibility</h3><p>In Java private, public, protected, default are the access specifiers. They define the level of access for each data member and the method and the class.</p><p>The following table demonstrates the level of access in Java program</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*NhiSc1A6SmnWPxGH.png" /></figure><p><strong>Inner Classes</strong></p><p>A class that is defined inside another class is an inner class.</p><pre><strong>class OuterClass{<br>   datamembers;<br>   class InnerClass{<br>      datamembers;<br>      methods;<br>   } <br>   outer class methods;<br>}</strong></pre><p>With the help of an inner class we can have access to the data and methods of outer class directly. However, we can limit the scope of innerclass with in the outer class itself.</p><p><strong>Local Classes</strong></p><p>An inner class whose definition is given inside the method of a class is nothng but a local class.</p><pre><strong>class OuterClass{<br>   datamembers;</strong></pre><pre><strong>   public returntype method(){<br>      class InnerClass{<br>          datamembers;<br>          methods;<br>       }<br>   } <br>   outer class methods;<br>}</strong></pre><p>Here in the class definition of the inner class is confined to the method in which it is defined.</p><h3>Exception Handling</h3><p>An abnormal solution i.e., raised during the program execution is nothing but exception. Every exception may lead to abnormal termination of program which may cause inconsistency in software reliability. Such exceptions may be handled by Java through a mechanism with which the program will be successfully executed even if an exception is raised.</p><p>When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, or other unforeseeable things. When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an <strong>exception</strong> (throw an error).</p><p>Normally, the run time errors may be due to the external failures like memory errors, device errors and power failures. However, exception handling is not applicable for such errors. It can only be done for the runtime errors that are caused/raised due to the elements in the program.</p><p>Java supports the exception handling extensive through a predefined class library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NNXxz4Uaj_BvZEZ7.png" /></figure><p>Every exception is a class in Java. Throwable is a super class for all Java exceptions. The main objective is to increase software reliability. No software should be terminated in the middle during the program execution for the trivial exceptions.</p><p>Exception handling is done by means of the following elements</p><ol><li>try block</li><li>catch block</li><li>finally block</li><li>throw</li><li>throws</li></ol><p><strong>Java try and catch</strong></p><p>The try statement allows you to define a block of code to be tested for errors while it is being executed.</p><p>The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.</p><p>The try and catch keywords come in pairs:</p><p><strong>Syntax</strong></p><pre><strong>try {<br>  //  </strong><strong><em>Block of code to try<br></em></strong><strong>}<br>catch(Exception </strong><strong><em>e</em></strong><strong>) {<br>  //  </strong><strong><em>Block of code to handle errors<br></em></strong><strong>}</strong></pre><p>Consider the following example:</p><p>This will generate an error, because <strong>myNumbers[10]</strong> does not exist.</p><pre><strong>public class Main {<br>  public static void main(String[ ] args) {<br>    int[] myNumbers = {1, 2, 3};<br>    System.out.println(myNumbers[10]); // error!<br>  }<br>}</strong></pre><p>The output will be something like this:</p><pre><strong>Exception in thread &quot;main&quot; java.lang.ArrayIndexOutOfBoundsException: 10 at Main.main(Main.java:4)</strong></pre><p>If an error occurs, we can use try...catch to catch the error and execute some code to handle it:</p><p><strong>Example</strong></p><pre><strong>public class Main {<br>  public static void main(String[ ] args) {<br>    try {<br>      int[] myNumbers = {1, 2, 3};<br>      System.out.println(myNumbers[10]);<br>    } catch (Exception e) {<br>      System.out.println(&quot;Something went wrong.&quot;);<br>    }<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>Something went wrong.</strong></pre><p><strong>Finally</strong></p><p>The finally statement lets you execute code, after try...catch, regardless of the result:</p><p><strong>Example</strong></p><pre><strong>public class Main {<br>  public static void main(String[] args) {<br>    try {<br>      int[] myNumbers = {1, 2, 3};<br>      System.out.println(myNumbers[10]);<br>    } catch (Exception e) {<br>      System.out.println(&quot;Something went wrong.&quot;);<br>    } finally {<br>      System.out.println(&quot;The &#39;try catch&#39; is finished.&quot;);<br>    }<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>Something went wrong.<br>The &#39;try catch&#39; is finished.</strong></pre><p><strong>The throw keyword</strong></p><p>The throw statement allows you to create a custom error. The throw statement is used together with an <strong>exception type</strong>. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:</p><p><strong>Example</strong></p><p>Throw an exception if <strong>age</strong> is below 18 (print “Access denied”). If age is 18 or older, print “Access granted”:</p><pre><strong>public class Main {<br>  static void checkAge(int age) {<br>    if (age &lt; 18) {<br>      throw new ArithmeticException(&quot;Access denied - You must be at least 18 years old.&quot;);<br>    }<br>    else {<br>      System.out.println(&quot;Access granted - You are old enough!&quot;);<br>    }<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    checkAge(15); // Set age to 15 (which is below 18...)<br>  }<br>}</strong></pre><p>The output will be:</p><pre><strong>Exception in thread &quot;main&quot; java.lang.ArithmeticException: Access denied - You must be at least 18 years old.<br>        at Main.checkAge(Main.java:4)<br>        at Main.main(Main.java:12)</strong></pre><p>If <strong>age</strong> was 20, you would <strong>not</strong> get an exception:</p><p><strong>Example</strong></p><pre><strong>checkAge(20);<br>The output will be:<br></strong><strong>Access granted - You are old enough!</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d95731556fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/packages-access-specifiers-exception-handling-3d95731556fe">Packages, Access Specifiers, Exception Handling</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Inheritance, Java Abstract Classes and Methods, Java Interfaces]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-inheritance-java-abstract-classes-and-methods-java-interfaces-24e9ff9cfcc0?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/24e9ff9cfcc0</guid>
            <category><![CDATA[java-abstract-classes]]></category>
            <category><![CDATA[java-inheritance]]></category>
            <category><![CDATA[java-interface]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Tue, 10 Nov 2020 11:22:15 GMT</pubDate>
            <atom:updated>2021-03-03T09:15:06.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Inheritance, Java Abstract Classes and Methods, Java Interfaces, Final Keyword</h3><h3>Inheritance</h3><p>It is the ability to extract the properties of one class into another class.</p><p>The main objective is to provide code reusability. It reduces the code redundancy to a greater extent which saves lot of developer time.</p><h4>Types of Inheritance:</h4><ol><li>Single</li><li>Multi level</li><li>Hierarchical</li></ol><p>Multiple and Hybrid inheritances can be achieved through <strong>Interfaces </strong>but not through <strong>classes</strong>.</p><p>In order to inherit one class to another class we use the keyword “extends”.</p><h3>Single Inheritance</h3><p>Here only two classes are involved in which one is parent class and the other one is the child class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*MPP7ncPBa0akqVqRW2Xwpg.png" /></figure><p>Once A is inherited into B we need not create object for class A. All the public methods of A can be accessed through object of class B.</p><p><strong>Syntax:</strong></p><pre><strong>class SuperClass{</strong></pre><pre><strong>       //body;<br>}<br>class SubClass extends SuperClass{ <br>      //body; <br>}</strong></pre><p>An example program for single Inheritance,</p><pre><strong>class Vehicle {<br>  protected String brand = &quot;Ford&quot;;        // Vehicle attribute<br>  public void honk() {                    // Vehicle method<br>    System.out.println(&quot;Tuut, tuut!&quot;);<br>  }<br>}<br><br>class Car extends Vehicle {<br>  private String modelName = &quot;Mustang&quot;;    // Car attribute<br>  public static void main(String[] args) {<br><br>    // Create a myCar object<br>    Car myCar = new Car();<br><br>    // Call the honk() method (from the Vehicle class) on the myCar object<br>    myCar.honk();<br><br>    // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class<br>    System.out.println(myCar.brand + &quot; &quot; + myCar.modelName);<br>  }</strong><br>}</pre><h3>Constructors Using Inheritance</h3><pre><strong>class CSE{<br>   private int tc;<br>   public CSE(int tc){<br>      this.tc = tc;<br>      System.out.print(this.tc);<br>   }<br>}</strong></pre><pre><strong>class CSE-A extends CSE{<br>   int ac;<br>   public CSE-A(int ac,int tc){<br>     super(tc);<br>     this.ac=ac;<br>     System.out.print(this.ac);<br>   }<br>}</strong></pre><pre><strong>public class CSEDemo{<br>  public static void main(String args[]){<br>      new CSE-A(64,2500;<br>  }<br>}</strong></pre><p>In order to call a super class method, the “Super” keyword is used.</p><h3>Multi-Level Inheritance</h3><p>In multilevel, a chain of classes are involved in Inheritance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*_-vNYw3TnS6ZerXt9xwUVA.png" /></figure><pre><strong>class Car{<br>   public Car()<br>   {<br>	System.out.println(&quot;Class Car&quot;);<br>   }<br>   public void vehicleType()<br>   {<br>	System.out.println(&quot;Vehicle Type: Car&quot;);<br>   }<br>}<br>class Maruti extends Car{<br>   public Maruti()<br>   {<br>	System.out.println(&quot;Class Maruti&quot;);<br>   }<br>   public void brand()<br>   {<br>	System.out.println(&quot;Brand: Maruti&quot;);<br>   }<br>   public void speed()<br>   {<br>	System.out.println(&quot;Max: 90Kmph&quot;);<br>   }<br>}<br>public class Maruti800 extends Maruti{<br><br>   public Maruti800()<br>   {<br>	System.out.println(&quot;Maruti Model: 800&quot;);<br>   }<br>   public void speed()<br>   {<br>	System.out.println(&quot;Max: 80Kmph&quot;);<br>   }<br>   public static void main(String args[])<br>   {<br>	 Maruti800 obj=new Maruti800();<br>	 obj.vehicleType();<br>	 obj.brand();<br>	 obj.speed();<br>   }<br>}</strong></pre><p><strong>Output:</strong></p><pre><strong>Class Car<br>Class Maruti<br>Maruti Model: 800<br>Vehicle Type: Car<br>Brand: Maruti<br>Max: 80Kmph</strong></pre><h3>Abstract Classes and Methods</h3><p>Data <strong>abstraction</strong> is the process of hiding certain details and showing only essential information to the user.<br>Abstraction can be achieved with either <strong>abstract classes</strong> or interfaces.</p><p>A class is a set of complete and incomplete methods is an<strong> abstract class.</strong></p><p>The abstract keyword is a non-access modifier, used for classes and methods:</p><ul><li><strong>Abstract class:</strong> is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).</li><li><strong>Abstract method:</strong> can only be used in an abstract class, and it does not have a body. The body is provided by the subclass (inherited from).</li></ul><p>Abstract is the keyword to be prefixed before the method name and the class name as well. If at least one method is incomplete the entire class becomes incomplete. The definition to the incomplete method can be given in corresponding subclasses.</p><p>Each subclass can have its own definition to the abstract methods in the super class. The purpose of the abstract classes is to act as a base class. As it is abstract class we cannot create object for it. How ever an object reference can be created.</p><p>Most often the abstract classes are preferable to use in hierarchy inheritance.</p><p>An abstract class can have both abstract and regular methods:</p><pre><strong>abstract class Animal {<br>  public abstract void animalSound();<br>  public void sleep() {<br>    System.out.println(&quot;Zzz&quot;);<br>  }<br>}</strong></pre><p>From the example above, it is not possible to create an object of the Animal class:</p><pre><strong>Animal myObj = new Animal(); // will generate an error</strong></pre><p>To access the abstract class, it must be inherited from another class. To use the abstract class it must be inherited from another class.</p><p><strong>Example</strong></p><pre><strong>// Abstract class<br>abstract class Animal {<br>  // Abstract method (does not have a body)<br>  public abstract void animalSound();<br>  // Regular method<br>  public void sleep() {<br>    System.out.println(&quot;Zzz&quot;);<br>  }<br>}</strong></pre><pre><strong>// Subclass (inherit from Animal)<br>class Pig extends Animal {<br>  public void animalSound() {<br>    // The body of animalSound() is provided here<br>    System.out.println(&quot;The pig says: wee wee&quot;);<br>  }<br>}</strong></pre><pre><strong>class MyMainClass {<br>  public static void main(String[] args) {<br>    Pig myPig = new Pig(); // Create a Pig object<br>    myPig.animalSound();<br>    myPig.sleep();<br>  }<br>}</strong></pre><p>Output:</p><pre><strong>The pig says: wee wee<br>Zzz</strong></pre><h3>Interfaces</h3><p>Another way to achieve abstraction in Java, is with interfaces.</p><p>An interface is a completely &quot;<strong>abstract class</strong>&quot; that is used to group related methods with empty bodies:</p><p><strong>Example</strong></p><pre><strong>// interface<br>interface Animal {<br>  public void animalSound(); // interface method (does not have a body)<br>  public void run(); // interface method (does not have a body)<br>}</strong></pre><p>To access the interface methods, the interface must be “implemented” (kind like inherited) by another class with the implements keyword (instead of extends). The body of the interface method is provided by the &quot;implement&quot; class:</p><p><strong>Example</strong></p><pre><strong>// Interface<br>interface Animal {<br>  public void animalSound(); // interface method (does not have a body)<br>  public void sleep(); // interface method (does not have a body)<br>}</strong></pre><pre><strong>// Pig &quot;implements&quot; the Animal interface<br>class Pig implements Animal {<br>  public void animalSound() {<br>    // The body of animalSound() is provided here<br>    System.out.println(&quot;The pig says: wee wee&quot;);<br>  }<br>  public void sleep() {<br>    // The body of sleep() is provided here<br>    System.out.println(&quot;Zzz&quot;);<br>  }<br>}</strong></pre><pre><strong>class MyMainClass {<br>  public static void main(String[] args) {<br>    Pig myPig = new Pig();  // Create a Pig object<br>    myPig.animalSound();<br>    myPig.sleep();<br>  }<br>}</strong></pre><p>Output:</p><pre><strong>The pig says: wee wee<br>Zzz</strong></pre><h3>Multiple Interfaces</h3><p>To implement multiple interfaces, separate them with a comma:</p><p><strong>Example</strong></p><pre><strong>interface FirstInterface {<br>  public void myMethod(); // interface method<br>}</strong></pre><pre><strong>interface SecondInterface {<br>  public void myOtherMethod(); // interface method<br>}</strong></pre><pre><strong>class DemoClass implements FirstInterface, SecondInterface {<br>  public void myMethod() {<br>    System.out.println(&quot;Some text..&quot;);<br>  }<br>  public void myOtherMethod() {<br>    System.out.println(&quot;Some other text...&quot;);<br>  }<br>}</strong></pre><pre><strong>class MyMainClass {<br>  public static void main(String[] args) {<br>    DemoClass myObj = new DemoClass();<br>    myObj.myMethod();<br>    myObj.myOtherMethod();<br>  }<br>}</strong></pre><p>Output</p><pre><strong>some text..<br>Some other Text...</strong></pre><h4>Final Keyword</h4><p>In Java, data member of a class, a method of a class and the class itself can be prefixed by a keyword “final”. The keyword plays a significant role in defining the three different components in the class.</p><ol><li>In case of a data member as final it behaves like a constant.</li></ol><pre><strong>final int MAX=5;<br>final define PI=3.14</strong></pre><p>2. A method is declared as final then that method cannot be overwritten.</p><pre><strong>class superA{<br>   final public void show(){<br>     System.out.println(&quot;Hello CSE-A&quot;);}<br>}</strong></pre><pre><strong>class SubB extends SuperA{<br>   public void show(){<br>      System.out.println(&quot;Hi CSE-A&quot;);}<br>}</strong></pre><pre><strong>public class OverRidingDemo{<br>  public static void main(String args[]){<br>    SuperA x = new SuperA();<br>    x.show();<br>    SubB y = new subB();<br>    y.show();<br> } <br>}</strong></pre><p>The above program gives compilation error as the final method is overridden in the subclass. In the absence of final keywords, the code runs successfully.</p><p>3. In case of class is declared as final it cannot be inherited. It means that the class becomes an independent class.</p><pre><strong>final class superA{<br>   public void show(){<br>     System.out.println(&quot;Hello CSE-A&quot;);}<br>}</strong></pre><pre><strong>class SubB extends SuperA{<br>   public void show(){<br>      System.out.println(&quot;Hi CSE-A&quot;);}<br>}</strong></pre><pre><strong>public class OverRidingDemo{<br>  public static void main(String args[]){<br>    SuperA x = new SuperA();<br>    x.show();<br>    SubB y = new subB();<br>    y.show();<br> } <br>}</strong></pre><p>In case of method over riding the following access privilege&#39;s should be followed.</p><ol><li>A public method can be overridden by a public method only.</li><li>A protected method can be overridden by either a protected or public method only.</li><li>A default method can be overridden by either a default or protected or public method only.</li><li>A private method can be overridden by either a private or default or protected or public method only.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e9ff9cfcc0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-inheritance-java-abstract-classes-and-methods-java-interfaces-24e9ff9cfcc0">Java Inheritance, Java Abstract Classes and Methods, Java Interfaces</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java OOPs Concept, Constructors, PolyMorphism, Constructor Overloading, Static Keyword]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-oops-concept-constructors-polymorphism-constructor-overloading-static-keyword-6bd610d6b582?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/6bd610d6b582</guid>
            <category><![CDATA[java-constructor]]></category>
            <category><![CDATA[overloadingconstructor]]></category>
            <category><![CDATA[static-keyword]]></category>
            <category><![CDATA[java-polymorphism]]></category>
            <category><![CDATA[java-oops-concept]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 13:03:27 GMT</pubDate>
            <atom:updated>2020-11-04T13:03:27.888Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Object Oriented Features</strong></h4><p>OOPs is a method of implementation where a co-operative collection of objects may be created, accessed and deployed.</p><p><strong>Features:</strong></p><ol><li>Classes and Objects</li><li>Data Abstraction</li><li>Data Encapsulation</li><li>Polymorphism</li><li>Inheritance</li><li>Persistence</li><li>Extendability</li><li>Message Passing</li></ol><h4><strong>Class</strong></h4><p>A class is a description of similar kind of objects or class is a blue print for several objects. A class is a logical entity that gives description of related objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*0JqYm6N-pvPcU-wtAIpOxQ.png" /></figure><h4><strong>Object</strong></h4><p>Object is a real world entity or An object is an instance of a class. An object is a physical entity which occupies certain space in memory.</p><h4>Data Abstraction</h4><p>It is a process of exhibiting the essential details by hiding the unwanted details on demand. It is a process of creating a new datatype called ADT [ Abstract Data Type].</p><h4><strong>Data Encapsulation</strong></h4><p>The process of wrapping up data and its methods into a single unit is nothing but encapsulation.</p><h4>Poly Morphism</h4><p>The ability to provide multiple definitions with same method signature.</p><h4>Inheritance</h4><p>The ability to extent the features of one class to another class is nothing but inheritance. The main Objective is code reusability.</p><h4>Persistence</h4><p>The process of making the object state permanent is nothing but persistence. The object by nature is temporary.</p><h4>Extendibility</h4><p>The ability to enhance the features or properties of the system without restructuring the existing system.</p><h4>Message Passing</h4><p>The process of invoking the method over an object is nothing but message passing.</p><p>An example program for demonstrating class and objects.</p><pre><strong>class Student{<br>  <br>  private int stno,year;<br>  private string name,branch;</strong></pre><pre><strong>  // method to set student details<br>  public setStudent() {<br>    stno = 1001;<br>    name = &quot;Raju&quot;;<br>    branch = &quot;CSE&quot;;<br>    year = 2;<br>  }<br><br>  // method to display the student details<br>  public void getStudent() {<br>    System.out.println(stno+&quot; &quot;+name+&quot; &quot;+br+&quot; &quot;+year);<br>  }<br>}<br><br>public class StudentDemo{<br>  public static void main(String[] args) {<br><br>    // create object s<br>    Student s = new Student();<br>   <br>    // set the student details<br>    // calling method setStudent()<br>    s.setStudent();<br><br>    // displaying the student details<br>    // calling method getStudent()<br>    s.getStudent();<br>  }<br>}</strong></pre><p><strong>Output:</strong></p><pre><strong>1001 Raju CSE 2</strong></pre><h3>Constructors</h3><p>A constructor is a special method that initializes an object of a class. Initialization is a process of assigning values to the data methods (or) instant variables of a class. Unless an object is initialized it cannot be kept in use.</p><p>A constructor initializes such objects when ever they are created. It is the first function to be executed when ever the object is created. It is executed only once and is invoked/implicitly called by the compiler.</p><p>The constructor must have the same name as its class name. Generally the constructor should be declared as public as it is meant for object initialization it doesn’t return any value. Even void should not be mentioned.</p><p>An example program for demonstrating Constructors</p><pre><strong>class Box{<br> private int height,width,depth;</strong></pre><pre><strong>//Constructor<br> public Box(){<br>  height=5;<br>  width=4;<br>  depth=3;<br> }</strong></pre><pre><strong>//A method for setting height <br> public void setHeight(int h){<br>  height=h;<br> }</strong></pre><pre><strong>//A method for setting width <br> public void setWidth(int w){<br>  width=w;<br> }</strong></pre><pre><strong>//A method for setting depth <br> public void setDepth(int d){<br>  depth=d;<br> }</strong></pre><pre><strong>//A method for setting all the attributes <br> public void setBox(int h,int w,int d){<br>  <br>  height=h;<br>  depth=d;<br>  width=w;<br> }</strong></pre><pre><strong>//A method for getting height <br> public int getHeight(){<br>  return height;<br> }</strong></pre><pre><strong>//A method for getting width <br> public int getWidth(){<br>  return width;<br> }</strong></pre><pre><strong>//A method for getting depth <br> public int getDepth(){<br>  return depth;<br> }</strong></pre><pre><strong>//A method for getting volume <br> public int getVolume(){<br>  return height*depth*width;<br> }</strong></pre><pre><strong>}</strong></pre><pre><strong>public class BoxDemo{<br> public static void main(String[] args) {<br>  Box b = new Box();<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());<br>  b.setBox(1,2,3);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());<br>  b.setHeight(10);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());<br>  b.setBox(12,22,23);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());</strong></pre><pre><strong>System.out.println(&quot;Displaying the values of Height, Width, Depth&quot;);<br>  System.out.println(b.getHeight() + &quot; &quot;+b.getWidth()+&quot; &quot;+b.getDepth());</strong></pre><pre><strong>}<br>}</strong></pre><p>Output:</p><pre><strong>Volume=60<br>Volume=6<br>Volume=60<br>Volume=6072<br>Displaying the values of Height, Width, Depth<br>12 22 23</strong></pre><h4><strong>Parameterized Constructors</strong></h4><p>A constructor that accepts data as an argument is a parameterized constructor.</p><pre><strong>class Box{<br> private int height,width,depth;</strong></pre><pre><strong>//Constructor<br> public Box(int h,int w,int d){<br>  height=h;<br>  width=w;<br>  depth=d;<br> }</strong></pre><pre><strong>//A method for setting height <br> public void setHeight(int h){<br>  height=h;<br> }</strong></pre><pre><strong>//A method for setting width <br> public void setWidth(int w){<br>  width=w;<br> }</strong></pre><pre><strong>//A method for setting depth <br> public void setDepth(int d){<br>  depth=d;<br> }</strong></pre><pre><strong>//A method for setting all the attributes <br> public void setBox(int h,int w,int d){<br>  <br>  height=h;<br>  depth=d;<br>  width=w;<br> }</strong></pre><pre><strong>//A method for getting height <br> public int getHeight(){<br>  return height;<br> }</strong></pre><pre><strong>//A method for getting width <br> public int getWidth(){<br>  return width;<br> }</strong></pre><pre><strong>//A method for getting depth <br> public int getDepth(){<br>  return depth;<br> }</strong></pre><pre><strong>//A method for getting volume <br> public int getVolume(){<br>  return height*depth*width;<br> }</strong></pre><pre><strong>}</strong></pre><pre><strong>public class BoxDemo{<br> public static void main(String[] args) {<br>  Box b = new Box(1,2,3);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());<br>  b.setBox(1,2,3);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());<br>  b.setHeight(10);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());<br>  b.setBox(12,22,23);<br>  System.out.println(&quot;Volume=&quot;+b.getVolume());</strong></pre><pre><strong>System.out.println(&quot;Displaying the values of Height, Width, Depth&quot;);<br>  System.out.println(b.getHeight() + &quot; &quot;+b.getWidth()+&quot; &quot;+b.getDepth());</strong></pre><pre><strong>}<br>}</strong></pre><p>Output:</p><pre><strong>Volume=60<br>Volume=6<br>Volume=60<br>Volume=6072<br>Displaying the values of Height, Width, Depth<br>12 22 23</strong></pre><h4>Static keyword</h4><p>In a class either data or method can be declared as static.</p><ol><li>In case of data as static the variable becomes sharable among all the object of the class has only one instance of the static variable is created in the method.</li><li>In case of method as static, it doesn’t use the object of a class. When a class doesn’t hold any data members then it is better to declare the method as static. A static method can be increased with the help of class name.</li><li>A class method can have access to static data only.</li></ol><pre><strong>class Account {<br>//define variables<br>private int accno;<br>private double balance; // balance for account<br>private double annualInterestRate; //stores the current interest rate<br>private static int minbal=500;</strong></pre><pre><strong>//no arg construtor<br>Account () {<br>    balance = 0.0;<br>    annualInterestRate = 0.0;<br>}<br>//constructor with specific id and initial balance</strong></pre><pre><strong>Account(int no, double newBalance) {<br>    accno= no;<br>    balance = newBalance;<br>}</strong></pre><pre><strong>Account(int newno, double newBalance, double newAnnualInterestRate) {<br>    accno= newno;<br>    balance = newBalance;<br>    annualInterestRate = newAnnualInterestRate;<br>}</strong></pre><pre><strong>//accessor/mutator methods for accno, balance, and     annualInterestRate</strong></pre><pre><strong>public int getaccno() {<br>    return accno;<br>}</strong></pre><pre><strong>public double getBalance() {<br>    return balance;<br>}</strong></pre><pre><strong>public double getAnnualInterestRate() {<br>    return annualInterestRate;<br>}</strong></pre><pre><strong>public void setAccNo(int acc_no) {<br>    accno= acc_no;<br>}</strong></pre><pre><strong>public void setBalance(double newBalance) {<br>    balance = newBalance;<br>}</strong></pre><pre><strong>public void setAnnualInterestRate(double newAnnualInterestRate) {<br>    annualInterestRate = newAnnualInterestRate;<br>}</strong></pre><pre><strong>//define method getMonthlyInterestRate<br>double getMonthlyInterestRate() {<br>    return annualInterestRate/12;<br>}</strong></pre><pre><strong>//define method withdraw<br>double withdraw(double amount) {</strong></pre><pre><strong>if((balance-amount)&gt;minbal)    <br>return balance -= amount;</strong></pre><pre><strong>else<br>return 0;<br>}<br>   <br>//define method deposit<br>double deposit(double amount) {<br>    return balance += amount;   <br>}<br>public static void changeMinBalance(){<br>minbal+=1000;<br>System.out.println(&quot;Minimum Balance Changed&quot;);</strong></pre><pre><strong>}</strong></pre><pre><strong>public class StaticDemo{<br><br>public static void main(String[] args) {<br>    <br>Account account1 = new Account(1122, 20000, .045);<br>account1.withdraw(2500);<br>account1.deposit(3000);<br><br>System.out.println(&quot;Account No:&quot; + account1.accno);<br>System.out.println(&quot;Balance:&quot; + account1.getBalance());<br>System.out.println(&quot;Interest Rate:&quot; + account1.getAnnualInterestRate());<br>System.out.println(&quot;Balance after withdraw of 2500:&quot; +       account1.getAnnualInterestRate());<br>System.out.println(&quot;Balance after deposit of 3000:&quot; + account1.getAnnualInterestRate());<br>System.out.println(&quot;Monthly Interest:&quot; + account1.accno);</strong></pre><pre><strong>Account.changeMinBalance();//Static method call<br>System.out.println(&quot;Process completed.&quot;);<br>}<br>}</strong></pre><p>Output</p><pre><strong>Account No:1122<br>Balance:20500.0<br>Interest Rate:0.045<br>Balance after withdraw of 2500:0.045<br>Balance after deposit of 3000:0.045<br>Monthly Interest:1122<br>Minimum Balance Changed<br>Process completed.</strong></pre><h4>Polymorphism</h4><p>It is the ability to provide multiple definations to the same method signature.</p><p>Here poly means many and morphism means forms.</p><p><strong>Advantages</strong></p><p>Polymorphism is used to build complex software system where the methods that form similar activity can have the same name.</p><p>The compiler is able to discriminate one method with another based on arguments. To be more specific the number of arguments, type of arguments and order of arguments.</p><p><strong>Syntax of a method:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*OeuKwu9JogQa-H0NnER2rw.png" /></figure><p>A method signature doesn’t include returntype. Here some of the valid and invalid methods are given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*vw0oaF6eW85w8bJIqfMcaw.png" /></figure><pre><strong>/* File name : Employee.java */<br>public class Employee {<br>   private String name;<br>   private String address;<br>   private int number;<br><br>   public Employee(String name, String address, int number) {<br>      System.out.println(&quot;Constructing an Employee&quot;);<br>      this.name = name;<br>      this.address = address;<br>      this.number = number;<br>   }<br><br>   public void mailCheck() {<br>      System.out.println(&quot;Mailing a check to &quot; + this.name + &quot; &quot; + this.address);<br>   }<br><br>   public String toString() {<br>      return name + &quot; &quot; + address + &quot; &quot; + number;<br>   }<br><br>   public String getName() {<br>      return name;<br>   }<br><br>   public String getAddress() {<br>      return address;<br>   }<br><br>   public void setAddress(String newAddress) {<br>      address = newAddress;<br>   }<br><br>   public int getNumber() {<br>      return number;<br>   }<br>}</strong></pre><p>Now suppose we extend Employee class as follows −</p><pre><strong>/* File name : Salary.java */<br>public class Salary extends Employee {<br>   private double salary; // Annual salary<br>   <br>   public Salary(String name, String address, int number, double salary) {<br>      super(name, address, number);<br>      setSalary(salary);<br>   }<br>   <br>   public void mailCheck() {<br>      System.out.println(&quot;Within mailCheck of Salary class &quot;);<br>      System.out.println(&quot;Mailing check to &quot; + getName()<br>      + &quot; with salary &quot; + salary);<br>   }<br>   <br>   public double getSalary() {<br>      return salary;<br>   }<br>   <br>   public void setSalary(double newSalary) {<br>      if(newSalary &gt;= 0.0) {<br>         salary = newSalary;<br>      }<br>   }<br>   <br>   public double computePay() {<br>      System.out.println(&quot;Computing salary pay for &quot; + getName());<br>      return salary/52;<br>   }<br>}</strong></pre><p>Now, you study the following program carefully and try to determine its output −</p><pre><strong>/* File name : VirtualDemo.java */<br>public class VirtualDemo {<br><br>   public static void main(String [] args) {<br>      Salary s = new Salary(&quot;Mohd Mohtashim&quot;, &quot;Ambehta, UP&quot;, 3, 3600.00);<br>      Employee e = new Salary(&quot;John Adams&quot;, &quot;Boston, MA&quot;, 2, 2400.00);<br>      System.out.println(&quot;Call mailCheck using Salary reference --&quot;);   <br>      s.mailCheck();<br>      System.out.println(&quot;\n Call mailCheck using Employee reference--&quot;);<br>      e.mailCheck();<br>   }<br>}</strong></pre><p>Output</p><pre><strong>Constructing an Employee<br>Constructing an Employee<br><br>Call mailCheck using Salary reference --<br>Within mailCheck of Salary class<br>Mailing check to Mohd Mohtashim with salary 3600.0<br><br>Call mailCheck using Employee reference--<br>Within mailCheck of Salary class<br>Mailing check to John Adams with salary 2400.0</strong></pre><p>Here, we instantiate two Salary objects. One using a Salary reference <strong>s</strong>, and the other using an Employee reference <strong>e</strong>.</p><p>While invoking <em>s.mailCheck()</em>, the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.</p><p>mailCheck() on <strong>e</strong> is quite different because <strong>e</strong> is an Employee reference. When the compiler sees <em>e.mailCheck()</em>, the compiler sees the mailCheck() method in the Employee class.</p><p>Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.</p><p>This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.</p><h4><strong>Constructor Overloading</strong></h4><p>As a constructor is also a mthod, it can also be overloaded.</p><p>If a class consists of multiple constructors it provides flexibility in creating objects for class.</p><pre><strong>// Java program to illustrate<br>// Constructor Overloading</strong></pre><pre><strong>class </strong><strong>Box{</strong></pre><pre><strong>double </strong><strong>width, height, depth;</strong></pre><pre><strong>// constructor used when all dimensions specified</strong></pre><pre><strong>Box(double </strong><strong>w, double </strong><strong>h, double </strong><strong>d)</strong></pre><pre><strong>{</strong></pre><pre><strong>width = w;<br>height = h;<br>depth = d;<br>}</strong></pre><pre><strong>// constructor used when no dimensions specified</strong></pre><pre><strong>Box()</strong></pre><pre><strong>{<br>   width = height = depth = 0;<br>}</strong></pre><pre><strong>// constructor used when cube is created<br>Box(double </strong><strong>len)</strong></pre><pre><strong>{<br>width = height = depth = len;</strong></pre><pre><strong>}<br>// compute and return volume</strong></pre><pre><strong>double </strong><strong>volume(){<br>   return </strong><strong>width * height * depth;<br>}<br>}</strong></pre><pre><strong>// Driver code</strong></pre><pre><strong>public </strong><strong>class </strong><strong>Test{</strong></pre><pre><strong>public </strong><strong>static </strong><strong>void </strong><strong>main(String args[]){</strong></pre><pre><strong>// create boxes using the various<br>// constructors</strong></pre><pre><strong>Box mybox1 = new </strong><strong>Box(10, 20, 15);<br>Box mybox2 = new </strong><strong>Box();<br>Box mycube = new </strong><strong>Box(7);<br>double </strong><strong>vol;</strong></pre><pre><strong>// get volume of first box<br>vol = mybox1.volume();<br>System.out.println(&quot; Volume of mybox1 is &quot; </strong><strong>+ vol);</strong></pre><pre><strong>// get volume of second box</strong></pre><pre><strong>vol = mybox2.volume();<br>System.out.println(&quot; Volume of mybox2 is &quot; </strong><strong>+ vol);</strong></pre><pre><strong>// get volume of cube<br>vol = mycube.volume();<br>System.out.println(&quot; Volume of mycube is &quot; </strong><strong>+ vol);</strong></pre><pre><strong>}<br>}</strong></pre><pre><strong>Output:</strong></pre><pre><strong>Volume of mybox1 is 3000.0<br>Volume of mybox2 is 0.0<br>Volume of mycube is 343.0</strong></pre><p><strong>Using this() in constructor overloading</strong></p><p><a href="http://quiz.geeksforgeeks.org/this-reference-in-java/">this() reference</a> can be used during constructor overloading to call default constructor implicitly from parameterized constructor. Please note, this() should be the first statement inside a constructor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bd610d6b582" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-oops-concept-constructors-polymorphism-constructor-overloading-static-keyword-6bd610d6b582">Java OOPs Concept, Constructors, PolyMorphism, Constructor Overloading, Static Keyword</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Methods, Java Parameters, Java Method Overloading, Java Scope, Java Recursion]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-methods-java-parameters-java-method-overloading-java-scope-java-recursion-c1389b7de5d?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1389b7de5d</guid>
            <category><![CDATA[method-overloading]]></category>
            <category><![CDATA[java-method]]></category>
            <category><![CDATA[java-parameter]]></category>
            <category><![CDATA[java-recursion]]></category>
            <category><![CDATA[java-scope]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Sat, 24 Oct 2020 04:20:49 GMT</pubDate>
            <atom:updated>2020-10-24T04:20:49.672Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>method</strong> is a block of code which only runs when it is called.</p><p>You can pass data, known as parameters, into a method.</p><p>Methods are used to perform certain actions, and they are also known as <strong>functions</strong>.</p><p>Why use methods? To reuse code: define the code once, and use it many times.</p><h3>Create a Method</h3><p>A method must be declared within a class. It is defined with the name of the method, followed by parentheses <strong>()</strong>. Java provides some pre-defined methods, such as System.out.println(), but you can also create your own methods to perform certain actions:</p><p>Creating a method inside MyClass:</p><pre><strong>public class MyClass {<br>  static void myMethod() {<br>    // code to be executed<br>  }<br>}</strong></pre><ul><li>myMethod() is the name of the method</li><li>static means that the method belongs to the MyClass class and not an object of the MyClass class. You will learn more about objects and how to access methods through objects later in this tutorial.</li><li>void means that this method does not have a return value. You will learn more about return values later in this chapter</li></ul><p><strong>Call a Method</strong></p><p>To call a method in Java, write the method’s name followed by two parentheses <strong>()</strong> and a semicolon<strong>;</strong></p><p>In the following example, myMethod() is used to print a text (the action), when it is called:</p><p>Inside main, call the myMethod() method:</p><pre><strong>public class MyClass {<br>  static void myMethod() {<br>    System.out.println(&quot;I just got executed!&quot;);<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    myMethod();<br>  }<br>}</strong></pre><pre><strong>// Outputs &quot;I just got executed!&quot;</strong></pre><p>A method can also be called multiple times:</p><pre><strong>public class MyClass {<br>  static void myMethod() {<br>    System.out.println(&quot;I just got executed!&quot;);<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    myMethod();<br>    myMethod();<br>    myMethod();<br>  }<br>}</strong></pre><pre><strong>// I just got executed!<br>// I just got executed!<br>// I just got executed!</strong></pre><h3>Java Method Parameters</h3><h4>Parameters and Arguments</h4><p>Information can be passed to methods as parameter. Parameters act as variables inside the method.</p><p>Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.</p><p>The following example has a method that takes a String called <strong>fname</strong> as parameter. When the method is called, we pass along a first name, which is used inside the method to print the full name:</p><pre><strong>public class MyClass {<br>  static void myMethod(String fname) {<br>    System.out.println(fname + &quot; Refsnes&quot;);<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    myMethod(&quot;Liam&quot;);<br>    myMethod(&quot;Jenny&quot;);<br>    myMethod(&quot;Anja&quot;);<br>  }<br>}<br>// Liam Refsnes<br>// Jenny Refsnes<br>// Anja Refsnes</strong></pre><p>When a <strong>parameter</strong> is passed to the method, it is called an <strong>argument</strong>. So, from the example above: fname is a <strong>parameter</strong>, while Liam, Jenny and Anja are <strong>arguments</strong>.</p><h4>Multiple Parameters</h4><p>You can have as many parameters as you like:</p><pre><strong>public class MyClass {<br>  static void myMethod(String fname, int age) {<br>    System.out.println(fname + &quot; is &quot; + age);<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    myMethod(&quot;Liam&quot;, 5);<br>    myMethod(&quot;Jenny&quot;, 8);<br>    myMethod(&quot;Anja&quot;, 31);<br>  }<br>}</strong></pre><pre><strong>// Liam is 5<br>// Jenny is 8<br>// Anja is 31</strong></pre><p>Note that when you are working with multiple parameters, the method call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.</p><h4>Return Values</h4><p>The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:</p><pre><strong>public class MyClass {<br>  static int myMethod(int x) {<br>    return 5 + x;<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    System.out.println(myMethod(3));<br>  }<br>}<br>// Outputs 8 (5 + 3)</strong></pre><p>This example returns the sum of a method’s <strong>two parameters</strong>:</p><pre><strong>public class MyClass {<br>  static int myMethod(int x, int y) {<br>    return x + y;<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    System.out.println(myMethod(5, 3));<br>  }<br>}<br>// Outputs 8 (5 + 3)</strong></pre><p>You can also store the result in a variable (recommended, as it is easier to read and maintain):</p><pre><strong>public class MyClass {<br>  static int myMethod(int x, int y) {<br>    return x + y;<br>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    int z = myMethod(5, 3);<br>    System.out.println(z);<br>  }<br>}<br>// Outputs 8 (5 + 3)</strong></pre><h4>A Method with If…Else</h4><p>It is common to use if...else statements inside methods:</p><pre><strong>public class MyClass {</strong></pre><pre><strong>  // Create a checkAge() method with an integer variable called age<br>  static void checkAge(int age) {</strong></pre><pre><strong>    // If age is less than 18, print &quot;access denied&quot;<br>    if (age &lt; 18) {<br>      System.out.println(&quot;Access denied - You are not old enough!&quot;);</strong></pre><pre><strong>    // If age is greater than 18, print &quot;access granted&quot;<br>    } else {<br>      System.out.println(&quot;Access granted - You are old enough!&quot;);<br>    }</strong></pre><pre><strong>  }</strong></pre><pre><strong>  public static void main(String[] args) {<br>    checkAge(20); // Call the checkAge method and pass along an age of 20<br>  }<br>}</strong></pre><pre><strong>// Outputs &quot;Access granted - You are old enough!&quot;</strong></pre><h3>Java Method Overloading</h3><h4>Method Overloading</h4><p>With<strong> method overloading</strong>, multiple methods can have the same name with different parameters:</p><pre><strong>int myMethod(int x)<br>float myMethod(float x)<br>double myMethod(double x, double y)</strong></pre><p>Consider the following example, which have two methods that add numbers of different type:</p><pre><strong>static int plusMethodInt(int x, int y) {<br>  return x + y;<br>}</strong></pre><pre><strong>static double plusMethodDouble(double x, double y) {<br>  return x + y;<br>}</strong></pre><pre><strong>public static void main(String[] args) {<br>  int myNum1 = plusMethodInt(8, 5);<br>  double myNum2 = plusMethodDouble(4.3, 6.26);<br>  System.out.println(&quot;int: &quot; + myNum1);<br>  System.out.println(&quot;double: &quot; + myNum2);<br>}</strong></pre><p>Instead of defining two methods that should do the same thing, it is better to overload one.</p><p>In the example below, we overload the plusMethod method to work for both int and double:</p><pre><strong>static int plusMethod(int x, int y) {<br>  return x + y;<br>}</strong></pre><pre><strong>static double plusMethod(double x, double y) {<br>  return x + y;<br>}</strong></pre><pre><strong>public static void main(String[] args) {<br>  int myNum1 = plusMethod(8, 5);<br>  double myNum2 = plusMethod(4.3, 6.26);<br>  System.out.println(&quot;int: &quot; + myNum1);<br>  System.out.println(&quot;double: &quot; + myNum2);<br>}</strong></pre><p><strong>Note:</strong> Multiple methods can have the same name as long as the number and/or type of parameters are different.</p><h3>Java Scope</h3><p>In Java, variables are only accessible inside the region they are created. This is called <strong>scope</strong>.</p><h4>Method Scope</h4><p>Variables declared directly inside a method are available anywhere in the method following the line of code in which they were declared:</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {</strong></pre><pre><strong>    // Code here CANNOT use x</strong></pre><pre><strong>    int x = 100;</strong></pre><pre><strong>    // Code here can use x<br>    System.out.println(x);<br>  }</strong><strong><br>}</strong></pre><h4>Block Scope</h4><p>A block of code refers to all of the code between curly braces {}. Variables declared inside blocks of code are only accessible by the code between the curly braces, which follows the line in which the variable was declared:</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {</strong></pre><pre><strong>    // Code here CANNOT use x</strong></pre><pre><strong>    { // This is a block</strong></pre><pre><strong>      // Code here CANNOT use x</strong></pre><pre><strong>      int x = 100;</strong></pre><pre><strong>      // Code here CAN use x<br>      System.out.println(x);</strong></pre><pre><strong>   } // The block ends here</strong></pre><pre><strong>  // Code here CANNOT use x</strong></pre><pre><strong>  }<br>}</strong></pre><p>A block of code may exist on its own or it can belong to an if, while or for statement. In the case of for statements, variables declared in the statement itself are also available inside the block&#39;s scope.</p><h3>Java Recursion</h3><p>Recursion is the technique of making a function call itself. This technique provides a way to break complicated problems down into simple problems which are easier to solve.</p><p>Recursion may be a bit difficult to understand. The best way to figure out how it works is to experiment with it.</p><h4>Recursion Example</h4><p>Adding two numbers together is easy to do, but adding a range of numbers is more complicated. In the following example, recursion is used to add a range of numbers together by breaking it down into the simple task of adding two numbers:</p><p>Use recursion to add all of the numbers up to 10.</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {<br>    int result = sum(10);<br>    System.out.println(result);<br>  }</strong><strong><br>  public static int sum(int k) {<br>    if (k &gt; 0) {<br>      return k + sum(k - 1);<br>    } else {<br>      return 0;<br>    }</strong><strong><br>  }</strong><strong><br>}</strong></pre><p>When the sum() function is called, it adds parameter k to the sum of all numbers smaller than k and returns the result. When k becomes 0, the function just returns 0. When running, the program follows these steps:</p><p>10 + sum(9)<br>10 + ( 9 + sum(8) )<br>10 + ( 9 + ( 8 + sum(7) ) )<br>…<br>10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)<br>10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0</p><p>Since the function does not call itself when k is 0, the program stops there and returns the result.</p><p><strong>Halting Condition</strong></p><p>Just as loops can run into the problem of infinite looping, recursive functions can run into the problem of infinite recursion. Infinite recursion is when the function never stops calling itself. Every recursive function should have a halting condition, which is the condition where the function stops calling itself. In the previous example, the halting condition is when the parameter k becomes 0.</p><p>It is helpful to see a variety of different examples to better understand the concept. In this example, the function adds a range of numbers between a start and an end. The halting condition for this recursive function is when <strong>end</strong> is not greater than <strong>start</strong>:</p><p>Use recursion to add all of the numbers between 5 to 10.</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {<br>    int result = sum(5, 10);<br>    System.out.println(result);<br>  }</strong><strong><br>  public static int sum(int start, int end) {<br>    if (end &gt; start) {<br>      return end + sum(start, end - 1);<br>    } else {<br>      return end;<br>    }<br>  }<br>}</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1389b7de5d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-methods-java-parameters-java-method-overloading-java-scope-java-recursion-c1389b7de5d">Java Methods, Java Parameters, Java Method Overloading, Java Scope, Java Recursion</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Strings]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-strings-dc6ccf16ef3b?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/dc6ccf16ef3b</guid>
            <category><![CDATA[java-strings]]></category>
            <category><![CDATA[string-tokenizer]]></category>
            <category><![CDATA[stringbuffer]]></category>
            <category><![CDATA[string-programs]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Fri, 23 Oct 2020 11:30:02 GMT</pubDate>
            <atom:updated>2020-10-23T11:30:02.649Z</atom:updated>
            <content:encoded><![CDATA[<h3>String Class</h3><p>In Java a string is a class rather than a character array. In other words, a character array is different from string in Java.</p><p>A string is an object with the set of characters. No null indicator at the end of the string object. A string class provides a set of methods that handles strings.</p><p>The following is the set of methods in Strings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skBbL_cjNaODGs-uljylmg.png" /></figure><p>For Example,</p><pre><strong>public class StringDemo{</strong></pre><pre><strong>     public static void main(String args[]){</strong></pre><pre><strong>          String p=args[0];<br>          String q=args[1];<br>          String r = p;<br>          if(p.equalsIgnoreCase(q))<br>             System.out.println(&quot;Same&quot;)<br>          else<br>            System.out.println(&quot;Different&quot;)<br>         <br>          if(p==q)<br>            System.out.println(&quot;Same&quot;)<br>          else<br>            System.out.println(&quot;Different&quot;)</strong></pre><pre><strong>         if(p==r)<br>            System.out.println(&quot;Same&quot;)<br>          else<br>            System.out.println(&quot;Different&quot;)</strong></pre><pre><strong>     }</strong></pre><pre><strong>}</strong></pre><p>Output:</p><pre><strong>CSE-A   CSE-A<br>Same<br>Different<br>Same</strong></pre><p>Note: equals() compares the content of the object where as == compares the object references.</p><p>An example of string sort:</p><pre><strong>import java.util.*;</strong></pre><pre><strong>public class StringSort{</strong></pre><pre><strong> public static void main(String args[]){</strong></pre><pre><strong>   int n,i,j;<br>   String k[];<br>   Scanner sc = new Scanner(System.in);<br>   System.out.println(&quot;Enter Number of strings&quot;);<br>   n=sc.nextInt();<br>   k=new String[n];<br>   System.out.println(&quot;Enter Names&quot;);<br>   for (i=0;i&lt;n;i++)<br>    k[i]=sc.next();</strong></pre><pre><strong>   for(i=0;i&lt;n;i++){<br>    for(j=i+1;j&lt;n;j++){<br>     if(k[i].compareTo(k[j])&gt;0)<br>     {<br>       String temp=k[i];<br>       k[i]=temp;<br>       k[j]=k[i];<br>     }<br>    }<br>   }</strong></pre><pre><strong>   System.out.println(&quot;After Sorting......&quot;);<br>   for(i=0;i&lt;n;i++)<br>     System.out.println(k[i]);<br>  }<br>}</strong></pre><p>Output,</p><pre><strong>Enter Number of strings<br>5<br>Enter Names<br>c cplus java python ruby<br>After Sorting......<br>c<br>cplus<br>java<br>python<br>ruby</strong></pre><p>Now let us see a program with the string methods to toggle the characters in the given string.</p><p>Program to convert the given string into toggle case.</p><pre><strong>import java.util.*;</strong></pre><pre><strong>public class Toggle{</strong></pre><pre><strong> public static void main(String[] args) {<br>  Scanner sc = new Scanner(System.in);<br>  char ch;<br>  System.out.println(&quot;Enter a String&quot;);<br>  String p = sc.next();</strong></pre><pre><strong>  for(int i=0;i&lt;p.length();i++)<br>  {<br>   ch=p.charAt(i);<br>   if((ch&gt;=65) &amp;&amp;(ch&lt;=90))<br>    ch=Character.toLowerCase(ch);<br>   else<br>    ch=Character.toUpperCase(ch);</strong></pre><pre><strong>   System.out.print(ch);<br>  }<br> }<br>}</strong></pre><p>Output, which we can do on the command prompt.</p><pre><strong>Enter a String<br>python</strong></pre><pre><strong>PYTHON</strong></pre><p>Now let us try to print prefixes and suffixes of the string:</p><pre><strong>import java.util.*;</strong></pre><pre><strong>public class StringsDemo{<br> public static void main(String[] args) {<br>  char ch;<br>  Scanner sc=new Scanner(System.in);<br>  <br>  System.out.println(&quot;Enter String&quot;);<br>  String p=sc.next();<br>  <br>  System.out.println(&quot;Prfixes of the string are&quot;);<br>  for(int i=0;i&lt;p.length();i++)<br>   System.out.println(p.substring(i));</strong></pre><pre><strong>  System.out.println(&quot;Sufixes of the string are&quot;);<br>  for(int i=0;i&lt;p.length();i++)<br>   System.out.println(p.substring(0,i));</strong></pre><pre><strong>}<br>}</strong></pre><p>Output will be,</p><pre><strong>Enter String<br>Andhrapradesh</strong></pre><pre><strong>Prfixes of the string are<br>Andhrapradesh<br>ndhrapradesh<br>dhrapradesh<br>hrapradesh<br>rapradesh<br>apradesh<br>pradesh<br>radesh<br>adesh<br>desh<br>esh<br>sh<br>h</strong></pre><pre><strong>Sufixes of the string are</strong></pre><pre><strong>A<br>An<br>And<br>Andh<br>Andhr<br>Andhra<br>Andhrap<br>Andhrapr<br>Andhrapra<br>Andhraprad<br>Andhraprade<br>Andhraprades</strong></pre><p>Now let us check whether the given string is palindrome or not.</p><pre><strong>import java.util.*;</strong></pre><pre><strong>public class Palindrome{<br> <br> public static void main(String[] args) {<br>  <br>  char ch;<br>  Scanner sc=new Scanner(System.in);<br>  <br>  System.out.println(&quot;Enter String&quot;);<br>  String p=sc.next();</strong></pre><pre><strong>String q = new String(p);<br>  <br>  System.out.println(&quot;Prfixes of the string are&quot;);<br>  <br>  StringBuffer sb=new StringBuffer(q);<br>  sb.reverse();</strong></pre><pre><strong>if(p.equals(sb.toString()))<br>   System.out.println(&quot;Palindrome&quot;);<br>  else<br>   System.out.println(&quot;Not Palindrome&quot;);</strong></pre><pre><strong>}<br>}</strong></pre><p>Output,</p><pre><strong>E:\Programs\Java&gt;java Palindrome<br>Enter String<br>abcdcba<br>Prfixes of the string are<br>Palindrome</strong></pre><pre><strong>E:\Programs\Java&gt;java Palindrome<br>Enter String<br>abcdef<br>Prfixes of the string are<br>Not Palindrome</strong></pre><p><strong>String Tokenizer:</strong></p><p>It divides or splits a string into token(sub strings) based on the given symbol. The symbol should be mentioned in terms of a string. It is present in java.util package. It consists of three methods:</p><ol><li>hasMoreTokens()</li><li>nextToken()</li><li>countTokens()</li></ol><p>Let us see this with an example.</p><p>Now let us try to divide a sentence into strings.</p><pre><strong>import java.util.*;</strong></pre><pre><strong>public class STDemo{<br> <br> public static void main(String[] args) {<br>  <br>  String msg=&quot;Today is a holiday&quot;;</strong></pre><pre><strong>  StringTokenizer st= new StringTokenizer(msg,&quot; &quot;);</strong></pre><pre><strong>  while(st.hasMoreTokens())<br>   System.out.println(st.nextToken());</strong></pre><pre><strong>}<br>}</strong></pre><p>Output will be,</p><pre><strong>Today<br>is<br>a<br>holiday</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc6ccf16ef3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-strings-dc6ccf16ef3b">Java Strings</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Conditions and Java Loops, Break Statement, Continue Statement, Java Arrays]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-conditions-and-java-loops-break-statement-continue-statement-java-arrays-5e511559756b?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/5e511559756b</guid>
            <category><![CDATA[continue-statement]]></category>
            <category><![CDATA[java-conditions]]></category>
            <category><![CDATA[java-array]]></category>
            <category><![CDATA[break-statement]]></category>
            <category><![CDATA[java-loop]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 10:23:44 GMT</pubDate>
            <atom:updated>2020-10-19T10:23:44.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Conditions and If Statements</h3><p>Java supports the usual logical conditions from mathematics:</p><ul><li>Less than: a &lt; b</li><li>Less than or equal to: a &lt;= b</li><li>Greater than: a &gt; b</li><li>Greater than or equal to: a &gt;= b</li><li>Equal to a == b</li><li>Not Equal to: a != b</li></ul><p>Java has the following conditional statements:</p><ul><li>Use if to specify a block of code to be executed, if a specified condition is true</li><li>Use else to specify a block of code to be executed, if the same condition is false</li><li>Use else if to specify a new condition to test, if the first condition is false</li><li>Use switch to specify many alternative blocks of code to be executed</li></ul><h3>The if Statement</h3><p>Use the if statement to specify a block of Java code to be executed if a condition is true.</p><h4>Syntax</h4><pre><strong>if (</strong><strong><em>condition</em></strong><strong>) {<br>  </strong><strong><em>// block of code to be executed if the condition is true</em></strong><strong><br>}</strong></pre><p>Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.</p><p>In the example below, we test two values to find out if 20 is greater than 18. If the condition is true, print some text:</p><pre><strong>if (20 &gt; 18) {<br>  System.out.println(&quot;20 is greater than 18&quot;);<br>}</strong></pre><p>We can also test variables:</p><pre><strong>int x = 20;<br>int y = 18;<br>if (x &gt; y) {<br>  System.out.println(&quot;x is greater than y&quot;);<br>}</strong></pre><p>In the example above we use two variables, <strong>x</strong> and <strong>y</strong>, to test whether x is greater than y (using the &gt; operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen that &quot;x is greater than y&quot;.</p><h4>The else Statement</h4><p>Use the else statement to specify a block of code to be executed if the condition is false.</p><pre><strong>if (</strong><strong><em>condition</em></strong><strong>) {<br>  </strong><strong><em>// block of code to be executed if the condition is true</em></strong><strong><br>} else {<br>  </strong><strong><em>// block of code to be executed if the condition is false</em></strong><strong><br>}</strong></pre><p>For example,</p><pre><strong>int time = 20;<br>if (time &lt; 18) {<br>  System.out.println(&quot;Good day.&quot;);<br>} else {<br>  System.out.println(&quot;Good evening.&quot;);<br>}<br>// Outputs &quot;Good evening.&quot;</strong></pre><p>In the example above, time (20) is greater than 18, so the condition is false. Because of this, we move on to the else condition and print to the screen &quot;Good evening&quot;. If the time was less than 18, the program would print &quot;Good day&quot;.</p><h4>The else if Statement</h4><p>Use the else if statement to specify a new condition if the first condition is false.</p><h4>Syntax</h4><pre><strong>if (</strong><strong><em>condition1</em></strong><strong>) {<br>  </strong><strong><em>// block of code to be executed if condition1 is true</em></strong><strong><br>} else if (</strong><strong><em>condition2</em></strong><strong>) {<br>  </strong><strong><em>// block of code to be executed if the condition1 is false and condition2 is true</em></strong><strong><br>} else {<br>  </strong><strong><em>// block of code to be executed if the condition1 is false and condition2 is false</em></strong><strong><br>}</strong></pre><p>For example,</p><pre><strong>int time = 22;<br>if (time &lt; 10) {<br>  System.out.println(&quot;Good morning.&quot;);<br>} else if (time &lt; 20) {<br>  System.out.println(&quot;Good day.&quot;);<br>} else {<br>  System.out.println(&quot;Good evening.&quot;);<br>}<br>// Outputs &quot;Good evening.&quot;</strong></pre><p>In the example above, time (22) is greater than 10, so the <strong>first condition</strong> is false. The next condition, in the else if statement, is also false, so we move on to the else condition since <strong>condition1</strong> and <strong>condition2</strong> is both false - and print to the screen &quot;Good evening&quot;.</p><p>However, if the time was 14, our program would print “Good day.”</p><h4>If…Else as Ternary Operator:</h4><p>There is also a short-hand if else, which is known as the <strong>ternary operator</strong> because it consists of three operands. It can be used to replace multiple lines of code with a single line. It is often used to replace simple if else statements:</p><pre><strong><em>variable = (condition) ? expressionTrue :  expressionFalse;</em></strong></pre><p>Instead of writing:</p><pre><strong>int time = 20;<br>if (time &lt; 18) {<br>  System.out.println(&quot;Good day.&quot;);<br>} else {<br>  System.out.println(&quot;Good evening.&quot;);<br>}</strong></pre><p>You can simply write:</p><pre><strong>int time = 20;<br>String result = (time &lt; 18) ? &quot;Good day.&quot; : &quot;Good evening.&quot;;<br>System.out.println(result);</strong></pre><ul><li>Print “Hello World” if x is greater than y.</li></ul><pre><strong>int x = 50;<br>int y = 10;<br> if(x &gt; y) {<br>  System.out.println(&quot;Hello World&quot;);<br>}</strong></pre><h3>Java Switch Statements</h3><p>Use the switch statement to select one of many code blocks to be executed.</p><pre><strong>switch(</strong><strong><em>expression</em></strong><strong>) {<br>  case x:<br>    </strong><strong><em>// code block</em></strong><strong><br>    break;<br>  case y:<br>    </strong><strong><em>// code block</em></strong><strong><br>    break;<br>  default:<br>    </strong><strong><em>// code block</em></strong><strong><br>}</strong></pre><p>This is how it works:</p><ul><li>The switch expression is evaluated once.</li><li>The value of the expression is compared with the values of each case.</li><li>If there is a match, the associated block of code is executed.</li><li>The break and default keywords are optional, and will be described later in this chapter</li></ul><p>The example below uses the weekday number to calculate the weekday name:</p><pre><strong>int day = 4;<br>switch (day) {<br>  case 1:<br>    System.out.println(&quot;Monday&quot;);<br>    break;<br>  case 2:<br>    System.out.println(&quot;Tuesday&quot;);<br>    break;<br>  case 3:<br>    System.out.println(&quot;Wednesday&quot;);<br>    break;<br>  case 4:<br>    System.out.println(&quot;Thursday&quot;);<br>    break;<br>  case 5:<br>    System.out.println(&quot;Friday&quot;);<br>    break;<br>  case 6:<br>    System.out.println(&quot;Saturday&quot;);<br>    break;<br>  case 7:<br>    System.out.println(&quot;Sunday&quot;);<br>    break;<br>}<br>// Outputs &quot;Thursday&quot; (day 4)</strong></pre><h4>The break Keyword</h4><p>When Java reaches a break keyword, it breaks out of the switch block.</p><p>This will stop the execution of more code and case testing inside the block.</p><p>When a match is found, and the job is done, it’s time for a break. There is no need for more testing.</p><p>A break can save a lot of execution time because it “ignores” the execution of all the rest of the code in the switch block.</p><h4>The default Keyword</h4><p>The default keyword specifies some code to run if there is no case match:</p><pre><strong>int day = 4;<br>switch (day) {<br>  case 6:<br>    System.out.println(&quot;Today is Saturday&quot;);<br>    break;<br>  case 7:<br>    System.out.println(&quot;Today is Sunday&quot;);<br>    break;<br>  default:<br>    System.out.println(&quot;Looking forward to the Weekend&quot;);<br>}<br>// Outputs &quot;Looking forward to the Weekend&quot;</strong></pre><p>Note that if the default statement is used as the last statement in a switch block, it does not need a break.</p><ul><li>Another example, Check the output</li></ul><pre><strong>int day = 2;<br>switch (day) {<br>  case 1:<br>    System.out.println(&quot;Saturday&quot;);<br>    break;<br>  case 2:<br>    System.out.println(&quot;Sunday&quot;);<br>    break;<br>}</strong></pre><h3>Loops</h3><p>Loops can execute a block of code as long as a specified condition is reached.</p><p>Loops are handy because they save time, reduce errors, and they make code more readable.</p><h3>Java While Loop</h3><p>The while loop loops through a block of code as long as a specified condition is true:</p><pre><strong>while (</strong><strong><em>condition</em></strong><strong>) {<br></strong><strong><em>  // code block to be executed</em></strong><strong><br>}</strong></pre><p>In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:</p><pre><strong>int i = 0;<br>while (i &lt; 5) {<br>  System.out.println(i);<br>  i++;<br>}</strong></pre><p><strong>Note:</strong> Do not forget to increase the variable used in the condition, otherwise the loop will never end!</p><h3>The Do/While Loop</h3><p>The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.</p><h4>Syntax</h4><pre><strong>do {<br></strong><strong><em>  // code block to be executed<br></em></strong><strong>}<br>while (</strong><strong><em>condition</em></strong><strong>);</strong></pre><p>The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:</p><pre><strong>int i = 0;<br>do {<br>  System.out.println(i);<br>  i++;<br>}<br>while (i &lt; 5);</strong></pre><p>Do not forget to increase the variable used in the condition, otherwise the loop will never end!</p><ul><li>Print i as long as i is less than 6.</li></ul><pre><strong>int i = 1;<br> while(i &lt; 6) {<br>  System.out.println(i); <br>  i++;<br>}</strong></pre><h3>For Loop</h3><p>When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:</p><h4>Syntax</h4><pre><strong>for (</strong><strong><em>statement 1</em></strong><strong>;</strong><strong><em> statement 2</em></strong><strong>;</strong><strong><em> statement 3</em></strong><strong>) {<br>  </strong><strong><em>// code block to be executed</em></strong><strong><br> }</strong></pre><p><strong>Statement 1</strong> is executed (one time) before the execution of the code block.</p><p><strong>Statement 2</strong> defines the condition for executing the code block.</p><p><strong>Statement 3</strong> is executed (every time) after the code block has been executed.</p><p>The example below will print the numbers 0 to 4:</p><pre><strong>for (int i = 0; i &lt; 5; i++) {<br>  System.out.println(i);<br>}</strong></pre><p>Statement 1 sets a variable before the loop starts (int i = 0).</p><p>Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.</p><p>Statement 3 increases a value (i++) each time the code block in the loop has been executed.</p><p>Another Example,</p><pre><strong>for (int i = 0; i &lt;= 10; i = i + 2) {<br>  System.out.println(i);<br>}</strong></pre><h4>For-Each Loop</h4><p>There is also a “<strong>for-each</strong>” loop, which is used exclusively to loop through elements in an <strong>array</strong>:</p><h4>Syntax</h4><pre><strong>for (</strong><strong><em>type</em></strong><strong> </strong><strong><em>variableName</em></strong><strong> : </strong><strong><em>arrayName</em></strong><strong>) {<br>  </strong><strong><em>// code block to be executed</em></strong><strong><br>}</strong></pre><p>The following example outputs all elements in the <strong>cars</strong> array, using a “<strong>for-each</strong>” loop:</p><pre><strong>String[] cars = {&quot;Volvo&quot;, &quot;BMW&quot;, &quot;Ford&quot;, &quot;Mazda&quot;};<br>for (String i : cars) {<br>  System.out.println(i);<br>}</strong></pre><ul><li>Use a for loop to print &quot;Yes&quot; 5 times.</li></ul><pre><strong>for(int i = 0; i &lt; 5; ) {<br>  System.out.println();<br>}</strong></pre><h3>Java Break</h3><p>You have already seen the break statement used in an earlier chapter of this tutorial. It was used to &quot;jump out&quot; of a switch statement.</p><p>The break statement can also be used to jump out of a <strong>loop</strong>.</p><p>This example jumps out of the loop when i is equal to 4:</p><pre><strong>for (int i = 0; i &lt; 10; i++) {<br>  if (i == 4) {<br>    break;<br>  }<br>  System.out.println(i);<br>}</strong></pre><h3>Java Continue</h3><p>The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.</p><p>This example skips the value of 4:</p><pre><strong>for (int i = 0; i &lt; 10; i++) {<br>  if (i == 4) {<br>    continue;<br>  }<br>  System.out.println(i);<br>}</strong></pre><h3>Break and Continue in While Loop</h3><p>You can also use break and continue in while loops:</p><h4>Break Example</h4><pre><strong>int i = 0;<br>while (i &lt; 10) {<br>  System.out.println(i);<br>  i++;<br>  if (i == 4) {<br>    break;<br>  }<br>}</strong></pre><h4>Continue Example</h4><pre><strong>int i = 0;<br>while (i &lt; 10) {<br>  if (i == 4) {<br>    i++;<br>    continue;<br>  }<br>  System.out.println(i);<br>  i++;<br>}</strong></pre><ul><li>To Stop the loop if i is 5.</li></ul><pre><strong>for (int i = 0; i &lt; 10; i++) {<br>  if (i == 5) {   <br>    break;<br>  }<br>  System.out.println(i);<br>}</strong></pre><h3>Java Arrays</h3><p>An array is a group of identical data items that are referred by a common name.</p><p>Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.</p><p>In Java, array is dynamic in nature. To declare an array, define the variable type with <strong>square brackets</strong>:</p><pre><strong>String[] cars;</strong></pre><p>We have now declared a variable that holds an array of strings. To insert values to it, we can use an array literal — place the values in a comma-separated list, inside curly braces:</p><pre><strong>String[] cars = {&quot;Volvo&quot;, &quot;BMW&quot;, &quot;Ford&quot;, &quot;Mazda&quot;};</strong></pre><p>To create an array of integers:</p><pre><strong>int[] myNum = {10, 20, 30, 40};</strong></pre><h4>Access the Elements of an Array</h4><p>You access an array element by referring to the index number. This statement accesses the value of the first element in cars:</p><pre><strong>String[] cars = {&quot;Volvo&quot;, &quot;BMW&quot;, &quot;Ford&quot;, &quot;Mazda&quot;};<br>System.out.println(cars[0]);<br>// Outputs Volvo</strong></pre><p><strong>Note:</strong> Array indexes start with 0: [0] is the first element. [1] is the second element, etc.</p><h4>Change an Array Element</h4><p>To change the value of a specific element, refer to the index number:</p><pre><strong>String[] cars = {&quot;Volvo&quot;, &quot;BMW&quot;, &quot;Ford&quot;, &quot;Mazda&quot;};<br>cars[0] = &quot;Open&quot;;<br>System.out.println(cars[0]);<br>// Now outputs Open instead of Volvo</strong></pre><h4><strong>Properties of an array:</strong></h4><ul><li>Array size is fixed, size can not be increased or decreasd on demand.</li><li>Index always begins at 0 and increments by 1.</li><li>No negative indexing.</li><li>Size must be atleast 1.</li></ul><h4>2D Arrays:</h4><p>An array with two subscripts which represents rows nd columns is a 2D array.</p><p><strong>Syntax:</strong></p><pre><strong>datatype arrayname[][];<br>arrayname = new datatype[rows][columns];</strong></pre><p>For Example,</p><pre><strong>int a[][];//Array reference<br>a = new int[3][4];//Memory Allocation</strong></pre><p><strong>Applications of 2D Arrays:</strong></p><ol><li>Matrices</li><li>Image Processing</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e511559756b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-conditions-and-java-loops-break-statement-continue-statement-java-arrays-5e511559756b">Java Conditions and Java Loops, Break Statement, Continue Statement, Java Arrays</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java]]></title>
            <link>https://medium.com/oops-oriented-java-programming-language/java-f236de2608c7?source=rss----55d8364a591a---4</link>
            <guid isPermaLink="false">https://medium.com/p/f236de2608c7</guid>
            <category><![CDATA[java-datatypes]]></category>
            <category><![CDATA[java-strings]]></category>
            <category><![CDATA[java-variables]]></category>
            <category><![CDATA[java-operator]]></category>
            <category><![CDATA[java-syntax]]></category>
            <dc:creator><![CDATA[Pravallika Devireddy]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 09:39:14 GMT</pubDate>
            <atom:updated>2020-10-19T10:26:15.919Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Introduction, Java Installation, Java Syntax, Java Variables, Java data types, Java Comments, Java Operators, Java Strings</h3><p>Java is a programming language introduced by Sun micro systems.</p><p>Java is used to develop mobile apps, web apps, desktop apps, games and much more.</p><h3>What is Java?</h3><p>Java is a popular programming language, created in 1995.</p><p>It is owned by Oracle, and more than <strong>3 billion</strong> devices run Java.</p><p>Initial name of Java is Oak.</p><p>The main success is platform independency is respective operating system, a Java program will be executed without trivial modifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*5XHtWCV8FnzQsrKuLa6oKA.jpeg" /></figure><p>It is used for:</p><ul><li>Mobile applications (specially Android apps)</li><li>Desktop applications</li><li>Web applications</li><li>Web servers and application servers</li><li>Games</li><li>Database connection</li><li>And much, much more!</li></ul><h3>Java Install</h3><p>Some PCs might have Java already installed.</p><p>To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):</p><pre><strong>C:\Users\<em>Your Name</em>&gt;java -version</strong></pre><p>If Java is installed, you will see something like this (depending on version):</p><pre><strong>java version &quot;1.8.0_261&quot;<br>Java(TM) SE Runtime Environment (build 1.8.0_261-b12)<br>Java HotSpot(TM) 64-Bit Server VM (build 25.261-b12, mixed mode)</strong></pre><p>If you do not have Java installed on your computer, you can download it for free at <a href="https://www.oracle.com/technetwork/java/javase/overview/index.html">oracle.com</a>.</p><h3>Setup for Windows</h3><p>To install Java on Windows:</p><ol><li>Go to “System Properties” (Can be found on Control Panel &gt; System and Security &gt; System &gt; Advanced System Settings)</li><li>Click on the “Environment variables” button under the “Advanced” tab</li><li>Then, select the “Path” variable in System variables and click on the “Edit” button</li><li>Click on the “New” button and add the path where Java is installed, followed by <strong>\bin</strong>. By default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when you installed it). In that case, You will have to add a new path with: <strong>C:\Program Files\Java\jdk-11.0.1\bin</strong><br>Then, click “OK”, and save the settings</li><li>At last, open Command Prompt (cmd.exe) and type <strong>java -version</strong> to see if Java is running on your machine</li></ol><p>Show how to install Java step-by-step with images »Step 2 »Step 3 »Step 4 »Step 5 »</p><h4>Structure of Java Program</h4><pre><strong>[Package Section]<br>&lt;import section&gt;<br>public class &lt;Classname&gt;{<br>    public static void main(string[] args){<br>        Local variable<br>        //body of main<br>    }<br>    [other method definations]<br>}<br>[other class definations]</strong></pre><h3>Usage of Java:</h3><p>In Java, every application begins with a class name, and that class must match the filename.</p><p>Let’s create our first Java file, called MyClass.java, which can be done in any text editor (like Notepad).</p><p>The file should contain a “Hello World” message, which is written with the following code:</p><p>MyClass.java</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {<br>    System.out.println(&quot;Hello World&quot;);<br>  }<br>}</strong></pre><p>Save the code in Notepad as “MyClass.java”. Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type</p><pre><strong>C:\Users\<em>Your Name</em>&gt;javac MyClass.java</strong></pre><p>This will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type “java MyClass” to run the file:</p><pre><strong>C:\Users\<em>Your Name</em>&gt;java MyClass</strong></pre><p>The output should read:</p><pre><strong>Hello World</strong></pre><h3>Java Syntax</h3><p>Explanation of Myclass.java</p><p>Every line of code that runs in Java must be inside a class. In our example, we named the class <strong>MyClass</strong>. A class should always start with an uppercase first letter.</p><p><strong>Note:</strong> Java is case-sensitive: “MyClass” and “myclass” has different meaning.</p><p>The name of the java file <strong>must match</strong> the class name. When saving the file, save it using the class name and add “.java” to the end of the filename. To run the example above on your computer, make sure that Java is properly installed.</p><h4>The main Method</h4><p>The main() method is required and you will see it in every Java program:</p><pre><strong>public static void main(String[] args)</strong></pre><p>Any code inside the main() method will be executed.</p><h4>System.out.println()</h4><p>Inside the main() method, we can use the println() method to print a line of text to the screen.</p><h3>Java Comments</h3><p>Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.</p><p>Single-line comments start with two forward slashes (//).</p><p>Any text between // and the end of the line is ignored by Java (will not be executed).</p><p>This example uses a single-line comment before a line of code:</p><pre><strong>// This is a comment<br>System.out.println(&quot;Hello World&quot;);</strong></pre><p>This example uses a single-line comment at the end of a line of code:</p><pre><strong>System.out.println(&quot;Hello World&quot;); // This is a comment</strong></pre><h4>Java Multi-line Comments</h4><p>Multi-line comments start with /* and ends with */.</p><p>Any text between /* and */ will be ignored by Java.</p><p>This example uses a multi-line comment (a comment block) to explain the code:</p><pre><strong>/* The code below will print the words Hello World<br>to the screen, and it is amazing */<br>System.out.println(&quot;Hello World&quot;);</strong></pre><h3>Java Variables</h3><p>Variables are containers for storing data values.</p><p>In Java, there are different <strong>types</strong> of variables, for example:</p><ul><li>String - stores text, such as &quot;Hello&quot;. String values are surrounded by double quotes</li><li>int - stores integers (whole numbers), without decimals, such as 123 or -123</li><li>float - stores floating point numbers, with decimals, such as 19.99 or -19.99</li><li>char - stores single characters, such as &#39;a&#39; or &#39;B&#39;. Char values are surrounded by single quotes</li><li>boolean - stores values with two states: true or false</li></ul><h4>Declaring (Creating) Variables</h4><p>To create a variable, you must specify the type and assign it a value:</p><p>Where <em>type</em> is one of Java’s types (such as int or String), and <em>variable</em> is the name of the variable (such as <strong>x</strong> or <strong>name</strong>). The <strong>equal sign</strong> is used to assign values to the variable.</p><p>To create a variable that should store text, look at the following example:</p><pre><strong>//Create a variable called name of type </strong><strong>String and assign it the //value &quot;John&quot;:</strong></pre><pre><strong>String name = &quot;John&quot;;<br>System.out.println(name);</strong></pre><pre><strong>//To create a variable that should store a number</strong></pre><pre><strong>int myNum = 15;<br>System.out.println(myNum);</strong></pre><pre><strong>//Change the value of </strong><strong>myNum from </strong><strong>15 to </strong><strong>20:<br></strong><strong>int myNum = 15;</strong></pre><pre><strong>myNum = 20;  // myNum is now 20<br>System.out.println(myNum);</strong></pre><h4>Final Variables</h4><p>However, you can add the final keyword if you don&#39;t want others (or yourself) to overwrite existing values (this will declare the variable as &quot;final&quot; or &quot;constant&quot;, which means unchangeable and read-only):</p><pre><strong>final int myNum = 15;<br>myNum = 20;//Generates an error: cannot assign a value to a final variable</strong></pre><h4>Display Variables</h4><p>The println() method is often used to display variables.</p><p>To combine both text and a variable, use the + character:</p><pre><strong>String name = &quot;John&quot;;<br>System.out.println(&quot;Hello &quot; + name);<br>//can also use the </strong><strong>+ character to add a variable to another //variable:<br></strong><strong>String firstName = &quot;John &quot;;<br>String lastName = &quot;Doe&quot;;<br>String fullName = firstName + lastName;<br>System.out.println(fullName);</strong></pre><pre><strong>//For numeric values, the </strong><strong>+ character works as a mathematical operator</strong><strong><br>int x = 5;<br>int y = 6;<br>System.out.println(x + y); // Print the value of x + y</strong></pre><h4>Java Identifiers</h4><p>All Java <strong>variables</strong> must be <strong>identified</strong> with <strong>unique names</strong>.</p><p>These unique names are called <strong>identifiers</strong>.</p><p>Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).</p><pre><strong>// Good<br>int minutesPerHour = 60;<br><br>// OK, but not so easy to understand what m actually is<br>int m = 60;</strong></pre><p>The general rules for constructing names for variables (unique identifiers) are:</p><ul><li>Names can contain letters, digits, underscores, and dollar signs</li><li>Names must begin with a letter</li><li>Names should start with a lowercase letter and it cannot contain whitespace</li><li>Names can also begin with $ and _ (but we will not use it in this tutorial)</li><li>Names are case sensitive (“myVar” and “myvar” are different variables)</li><li>Reserved words (like Java keywords, such as int or boolean) cannot be used as names</li></ul><h3>Java Data Types</h3><p>As already discussed, we need to define a variable using data type.</p><pre><strong>int myNum = 5;               // Integer (whole number)<br>float myFloatNum = 5.99f;    // Floating point number<br>char myLetter = &#39;D&#39;;         // Character<br>boolean myBool = true;       // Boolean<br>String myText = &quot;Hello&quot;;     // String</strong></pre><p>Data types are divided into two groups:</p><ul><li>Primitive data types — includes byte, short, int, long, float, double, boolean and char</li><li>Non-primitive data types — such as strings,arrays,classes.</li></ul><h4>Java Type Casting</h4><p>Type cating can be both</p><ul><li>Automatic</li><li>Manual</li></ul><p>Automatically can be done as shown below,</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {<br>    int myInt = 9;<br>    double myDouble = myInt; // Automatic casting: int to double<br><br>    System.out.println(myInt);      // Outputs 9<br>    System.out.println(myDouble);   // Outputs 9.0<br>  }<br>}</strong></pre><p>Manually is done as shown below,</p><pre><strong>public class MyClass {<br>  public static void main(String[] args) {<br>    double myDouble = 9.78;<br>    int myInt = (int) myDouble; // Manual casting: double to int</strong></pre><pre><strong>System.out.println(myDouble);   // Outputs 9.78<br>    System.out.println(myInt);      // Outputs 9<br>  }<br>}</strong></pre><h4>Java Buzzwords</h4><ol><li>Simple and Secured.</li><li>Robust is about regarding errors.</li><li>Architecture is neutral.</li><li>Strongly typed.</li><li>Interpreted — There is no executable file for java. Java consists both compiler and interpreter.</li><li>Dynamic</li><li>Average Multithreaded — Belongs to OS.</li><li>Object Oriented</li><li>High Performance</li><li>Distributed.</li></ol><h3>Java Operators</h3><p>Operators are used to perform operations on variables and values. Java divides the operators into the following groups:</p><ul><li>Arithmetic operators</li><li>Assignment operators</li><li>Comparison operators</li><li>Logical operators</li><li>Bitwise operators</li></ul><p><strong>Arithmetic operators:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*k0JVL-sjAcI9USuWMi9pHQ.png" /></figure><p><strong>Assignment Operators:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*6LQo2rw_zf1uf3TpZ382ew.png" /></figure><p><strong>Comparison Operators:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*tGTVnyiFKgTid9zqrUPZUQ.png" /></figure><p><strong>Logical Operators:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*k5hvqyzVhu6Drkir0_h8hw.png" /></figure><p><strong>Bitwise Operators:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*Sor78aCuW3spinEu5rvzPw.png" /></figure><h3>Java Strings</h3><p>Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes:</p><p>Create a variable of type String and assign it a value:</p><pre><strong>String greeting = &quot;Hello&quot;;</strong></pre><h4>String Length</h4><p>A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method:</p><pre><strong>String txt = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;<br>System.out.println(&quot;The length of the txt string is: &quot; + txt.length());</strong></pre><h4>String Methods</h4><p>There are many string methods available, for example toUpperCase() and toLowerCase():</p><pre><strong>String txt = &quot;Hello World&quot;;<br>System.out.println(txt.toUpperCase());   // Outputs &quot;HELLO WORLD&quot;<br>System.out.println(txt.toLowerCase());   // Outputs &quot;hello world&quot;</strong></pre><h4>Finding a Character in a String</h4><p>The indexOf() method returns the <strong>index</strong> (the position) of the first occurrence of a specified text in a string (including whitespace):</p><pre><strong>String txt = &quot;Please locate where &#39;locate&#39; occurs!&quot;;<br>System.out.println(txt.indexOf(&quot;locate&quot;)); // Outputs 7</strong></pre><p>Java counts positions from zero.<br>0 is the first position in a string, 1 is the second, 2 is the third …</p><h4>String Concatenation</h4><p>The + operator can be used between strings to combine them. This is called <strong>concatenation</strong>:</p><pre><strong>String firstName = &quot;John&quot;;<br>String lastName = &quot;Doe&quot;;<br>System.out.println(firstName + &quot; &quot; + lastName);</strong></pre><p>Note that we have added an empty text (“ “) to create a space between firstName and lastName on print. You can also use the concat() method to concatenate two strings:</p><pre><strong>String firstName = &quot;John &quot;;<br>String lastName = &quot;Doe&quot;;<br>System.out.println(firstName.concat(lastName));</strong></pre><h3>Special Characters</h3><p>Because strings must be written within quotes, Java will misunderstand this string, and generate an error:</p><pre><strong>String txt = &quot;We are the so-called &quot;Vikings&quot; from the north.&quot;;</strong></pre><p>The solution to avoid this problem, is to use the <strong>backslash escape character</strong>.</p><p>The backslash (\) escape character turns special characters into string characters:</p><p>The sequence \&quot; inserts a double quote in a string:</p><pre><strong>String txt = &quot;We are the so-called \&quot;Vikings\&quot; from the north.&quot;;</strong></pre><p>The sequence \&#39; inserts a single quote in a string:</p><pre><strong>String txt = &quot;It\&#39;s alright.&quot;;</strong></pre><p>The sequence \\ inserts a single backslash in a string:</p><pre><strong>String txt = &quot;The character \\ is called backslash.&quot;;</strong></pre><h4>Adding Numbers and Strings</h4><p>WARNING!</p><p>Java uses the + operator for both addition and concatenation.</p><p>Numbers are added. Strings are concatenated.</p><p>If you add two numbers, the result will be a number:</p><pre><strong>int x = 10;<br>int y = 20;<br>int z = x + y;      // z will be 30 (an integer/number)</strong></pre><p>If you add two strings, the result will be a string concatenation:</p><pre><strong>String x = &quot;10&quot;;<br>String y = &quot;20&quot;;<br>String z = x + y;   // z will be 1020 (a String)</strong></pre><p>If you add a number and a string, the result will be a string concatenation:</p><pre><strong>String x = &quot;10&quot;;<br>int y = 20;<br>String z = x + y;   // z will be 1020 (a String)</strong></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f236de2608c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/oops-oriented-java-programming-language/java-f236de2608c7">Java</a> was originally published in <a href="https://medium.com/oops-oriented-java-programming-language">OOPS oriented Java Programming Language</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>