Skip to main content

Posts

Showing posts with the label Java

Java Program to Reverse a String

There are 2 ways to reverse a string  String reversal without using function String reversal with function String reversal without using function package stringReversal; import java.util.Scanner; public class StringReversal { int stringLength; static String stringToReverse; String reversedString=""; public String stringReverse(String name) { stringLength = name.length(); for(int i=stringLength-1; i>=0;i--) { reversedString+=name.charAt(i); } return reversedString; } public static void main(String[] args) { StringReversal stringReversal = new StringReversal(); Scanner scanner = new Scanner(System.in); System.out.print("Enter the string to reverse :"); stringToReverse = scanner.nextLine(); System.out.println("Reversed String is :" +stringReversal.stringReverse(stringToReverse)); } } Output Enter the string to reverse :Make the string reversed Reversed String is :desrever gnirts eht ekaM String ...

String in Java

    Strings are nothing but the sequence of characters that are widely used in the programs. A string is one of the default class in Java which had the capability of binding the characters to form a word. When JVM finds String name in the program it will create an object for the String class.      There is no need for a developer to create an object for the String class. Variable with type String class Display { public static void main(String[] args) { String b = "This is a variable of type string" System.out.println(b) } } Method with String type public class DisplayCheck { static String check = "String check"; String display(String s) { return s; } public static void main(String[] args) { DisplayCheck d = new DisplayCheck(); System.out.println(d.display(check)); } } Below is some of the list of methods that can be used to do various actions on the String .length() - This is used to find the length of the string .concat() - Using t...

Exception Handling in Java

  Handling the exception occurred during runtime or compile time is important to avoid user frustration. To handle these exceptions there are certain ways to do that. By using Try and Catch blocks Syntax      try {          -- Code that may cause exception --      }      catch (java.lang.Exception e) {          -- Next line of the code that causes exception --      }      finally {          -- Important code that should run whether the exception is handled or not --       }   try - This keyword is used to put the code that may cause the exception, if the code in this block causes an exception, it will execute code in the catch block, or else code in the try block will get executed catch - This block must be placed after the try block. If an exception occurred in the try block, the code in the catch block will ...

Exception in Java

      Exception means abnormal condition. When this kind of condition occurs in the program during runtime, it will throw an object in the runtime. This will affect the user experience so, this needs to be handled in various ways.     On many sites, we have seen messages under the fields. For example, according to the requirement, the age field should accept only numeric values, if the user enters alphabets in it, it will show an error message as "This field should accept only numeric value". Rather than termination of the program, it allows user to process their requirements. Like this example, all exceptions need to be handled to avoid a bad user experience. Types of Exceptions There are 3 types of exceptions Checked Exceptions Unchecked Exceptions Errors Below is the hierarchy of these classes java.lang Object Throwable Errors StackOverflowError VirtualMachineError OutOfMemoryError Exceptions IOException SQLException ClassNotFoundException Runtime exception(U...

Classes and Object in Java

Class -   This is a basic and important concept in Java. Classes are the blueprint of variables and methods to describe its behavior and it helps the compiler in creating the object. Syntax for creating a class class ClassName{ } Objects - Objects are the reference for the variables and methods that are in the class.  Syntax for creating an object ClassName referenceName = new ClassName(); Types of classes in Java Concrete class Abstract class Inner class Static class Final class POJO class 1. Concrete class     This type of class does not contain any abstract method and these classes will contain its own method implementation.  Sample Program --------------------------------------------------------------------------------------------------------------------     public class  ClassAndObjects  {         int varr = 6;         void display() {        ...

Data types in Java

     The name itself defines it as  Data type.  It tells the compiler or interpreter that the data as belonging to this type. Let's discuss it's type in detail. Types of data types Primitive datatype Non-primitive datatype 1. Primitive datatype     The main reason for this type is to make the compiler knows the type of data. This is predefined and in java, it is mandatory to mention data type for the variables. Below are the primitive data types Integer byte - Stores number from -128 to 127 short - Stores number from -32768 to 32767 int - Stores data between  -2,147,483,648 to 2,147,483,647 long - Stores data between -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Float float - Stores fractional number and can store upto 6 to 7 digits double - Stores fractional number and can store upto 15 digits boolean - Can store true of false char - Can store single character or ASCII value Example byte a = 1; short b = 2; int ...

Arrays in Java

     By using this array concept, we can store a fixed number of elements of the same data type . There are many ways to declare an array and there are many use cases around this concept. In array, data will be stored starting from 0 Let's see one by one. Types of array Single dimensional array Multidimensional array 1. Single dimensional array     In this type, the index of the array will be in a linear manner.  Array declaration Syntax DataType[]  variable = new  DataType[Defined length]; DataType  [] variable = new  DataType[Defined length]; DataType  variable []  = new  DataType[Defined length]; If the values are known this can be defined as like in below DataType[]  variable = new  DataType[]{data 1, data 2, etc.,}; Here the length of the array will depend on the number of data given in the above syntax. Example String[] arr = new String[5]; String []arr = new String[] {"a","b"}; In the above example, data ...

Constructors in Java

      This concept had similarities to methods but not the same as the method. These constructors are used to instantiate the object created for that class. If the program already had used the defined constructor, the compiler will use it. If there is not constructor mentioned in the code compiler will add the default constructor. The constructor name should be the same as the class name. Types of constructor Default Constructor No Argument Constructor Parameterized Constructor 1. Default Constructor     If there is no implementation made on the constructor of the class is made it is known as the default constructor. In this scenario, While creating an object for that class, the compiler will create a default constructor to instantiate the variables.     In this scenario, there is no implementation made on the constructor. So, the Compiler will create a new default constructor. 2. No Argument Constructor     In this concept, some user-defined...

Abstraction in Java

    By using this concept we can able to hide the main functionality and shown only what the implementation does. Like in the smartphone we don't know how the feature is implemented but the user can able to see and use the outcome for those implementations. In Encapsulation, data will be hidden and in abstraction, implementation will be hidden.     By using Interface, abstract classes, and abstract methods we can able to achieve this. By using this concept, can able to identify only the required characteristics and can omit unwanted implementations. Key points to note If a class is a method that is declared as Abstract  without any implementation then it will become an abstract class and abstract method. If a class contains any abstract method, the class should be declared as abstract If any class inherits an abstract class, it should give implementation for all the abstract methods of the parent class or make the child class itself an abstract Should not able t...

Polymorphism in Java

Polymorphism By using this concept we can able to perform the same action in different ways This is achieved by using method overloading and method overriding Types of Polymorphism Runtime Polymorphism or Dynamic Polymorphism Compile-time Polymorphism or Static Polymorphism or early binding 1. Runtime Polymorphism or Dynamic Polymorphism      This is achieved using method is overridden and method overriding. Assume a class is having some method implementation and in your program, if you want to do your own implementation with the same method name, you need to override the implemented method.  Let us discuss in detail using the sample program ---------------------------------------------------------------------------------------------------------------- package oops; class Boss{ //This is overridden method public void project() { System.out.println("This project is from overridden method"); } } public class Polymorphism extends Boss { //This is overriding m...

Encapsulation in Java

Encapsulation This is one of the interesting concepts. By using this, data will be surrounded by a protective shield and restricts access for this data over other classes. It hides the data sent through it.  This example is the most relative thing for this concept so all people are using this example. Assume a capsule with medicine stuff. It binds all medicines in a single capsule and hides what the medicines are inside.  This can be achieved by declaring a private variable and using the  getters and setters method Declare the variable as private Get the value for the variable in the setter method Get the variable value using the getter method Read and write access By using this concept we can able to make the system set the value for the private variable and can get the value of the saved variable. ------------------------------------Sample program ------------------------------------ package oops; class ParentClass{ private String temp; public void getTemp() { S...

Inheritance in Java

Inheritance It explains with its name itself, by using this feature we can able to use all properties of one class into another class using  extends  keyword.  Key terms in this concept are parent class or superclass or base class and child class or subclass or derived class.  Types of Inheritance Single Inheritance Multilevel Inheritance Hierarchical Inheritance Multiple Inheritance  Hybrid Inheritance  1. Single Inheritance It will have only 1 parent or superclass and 1 child class. Properties of the parent class are accessible in the child class using the  extends  keyword Using this concept we can able to use methods from the parent class without creating an object for the parent class.  Sample Program Class name:  TutorialInheritance.java                                                 ...