Posts

Showing posts with the label Classes and Objects

Program to implement STACK and its operations

A  Stack  is a linear data structure in which all insertions or deletions are takes place at only one end rather than in the middle. This end is called as  top  of stack. For example – a stack of coins, a stack of plates. As the elements are inserted (added) or deleted (removed) from one end only it is called as  FILO (First In Last Out)  or  LIFO (Last In First Out)  lists. If stack is full (no space for new element) and we are inserting new element then such condition is called as  Stack Overflow . If stack is empty (no element in stack) and we are deleting an element at top of stack then such condition is called as  Stack Underflow . This program demonstrate the operations on STACK. When the new element is added in Stack then value of "top" is incremented by 1 and if we delete an element from Stack then the value of "top" is decremented by 1. PROGRAM import java.util.Scanner; class MyStack { private final int MAX_SIZE...

Program to check whether the given string is palindrome or not

Palindrome  is a string, which when read in both forward and backward way is the same. For example, "radar" is palindrome but "abc" is not palindrome. PROGRAM import java.util.Scanner; class CheckStringForPalindrome { public static void main(String args[]) { Scanner s=new Scanner(System.in); System.out.print("Enter the String : "); String originalStr=s.nextLine(); String reverseStr=""; for(int i=originalStr.length()-1;i>=0;i--) { reverseStr = reverseStr + originalStr.charAt(i); } if(reverseStr.equalsIgnoreCase(originalStr) == true) System.out.println("String is Palindrome."); else System.out.println("String is not Palindrome."); } } OUTPUT 1 C:\>javac CheckStringForPalindrome.java C:\>java CheckStringForPalindrome.java Enter the String : Hello String is not Palindrome. OUTPUT 2 C:\>javac CheckStringForPalindrome.java C:\>java CheckStringForPalindrome.java E...

Program to demonstrate the use of "StringTokenizer" class

The  StringTokenizer  class allows an application to break a string into tokens. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments. A StringTokenizer object internally maintains a current position within the string to be tokenized. A token is returned by taking a substring of the string that was used to create the StringTokenizer object. The following example demonstrate the use of the tokenizer. The code StringTokenizer st = new StringTokenizer("this is a demo"); while (st.hasMoreTokens( )) { System.out.println(st.nextToken( )); } prints the following output: this is a demo Some of the methods of  StringTokenizer  class are given below : boolean hasMoreTokens( ) :  Tests if there are more tokens available from this tokenizer's string. boolean hasMoreElements( ) :  It returns the same value as the hasMoreTokens method. String nextToken( ) :  It ...

Program to accept number from user and convert it into binary by using wrapper class method

A variable of primitive data type is by default passed by value and not by reference. If you need to consider such variables of primitive data type as reference types then the solution is wrapper classes provided by Java. These classes are used to wrap the data in a new object which contains the value of that variable.  Wrapper class  in java provides the mechanism to convert primitive data type into object and object into primitive data type.  The list of eight wrapper classes are given below: Primitive Type Wrapper class boolean Boolean char Character byte Byte short Short int Integer long Long float Float double Double For example, we wrap the number 34 in an  Integer  object in the following way: Integer intObject = new Integer (34); The  Integer  class is the wrapper class that has been provided for the  int  data type. Here we have used one of the method of  Integer  wrapper class  toBinaryString...

Program to accept first name, middle name and surname in three different strings and then concatenate the three strings to make full name

A  StringBuffer  class is like a String, but can be modified. StringBuffer class is mutable. StringBuffer is fast and consumes less memory when you concat strings. For example, // Constructs string buffer with no characters in it // and an initial capacity of 16 characters. StringBuffer s1 = new StringBuffer( ); OR // Constructs a string buffer with no characters in it and the specified // initial capacity to 5. StringBuffer s2 = new StringBuffer(5); // Constructs a string buffer that contains the three characters. // The initial capacity of the string buffer is 16 plus // the length of the "abc" string in short it is 19. StringBuffer s3 = new StringBuffer("abc"); Here we have used the  append(String str)  method of  StringBuffer  class which appends the specified string to this character sequence. In program we get first name, middle name and last name from user and then append them in a StringBuffer object. PROGRAM import java...

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

This program demonstrates you the array of objects.  Array of object  is the collection of objects of the same class. The given syntax will define an array of reference therefore assign object to individual reference in the array to declare the array of object. The syntax to define array of object is: <class-name> <array-name> [size]; For example, the following statement will define an array of object having size 6 references to the class  Box . Box b[6]; For creating an array of objects (allocating memory) you have to write down the following statements for (int i=0; i<6; i++) { b[i] = new Box(); // Assigning object to individual reference in the array. } PROGRAM import java.util.Scanner; public class Employee { int empid; String name; float salary; public void getInput() { Scanner in = new Scanner(System.in); System.out.print("Enter the empid :: "); empid = in.nextInt(); System.out.print("Enter the name :: ");...

Program for Constructor Overloading

Constructor  is a special type of method which enables to initialize an object when it is first created. It has the same name as the class name in which it is declared. It does not specify a return type not even void. It has following syntax: // Default constructor <class-name> ( ) { // Statements } OR // Parameterized constructor <class-name> (parameter list) { // Statements } Like methods, constructors can also be overloaded.  Constructor overloading  is way of having more than one constructor which does different tasks. For e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and capacity increment then you can simply use default constructor of Vector class like this Vector v = new Vector( ); PROGRAM class ConstructorOverloading { int a,b; // data members declaration ConstructorOverloading() // default constructor initialized to zero { a = b = 0; } ConstructorOverloading(int x,int...

Program to accept principal amount, rate of interest, no. of years from the user and display the simple interest

This is an interactive Java program which accept Input from User using  java.util.Scanner  class. By the way calSI() method is used to calculate the simple interest. The formula to calculate Simple Interest is given below: simple_interest = (total_amount * rate * no_of_years) / 100 PROGRAM import java.lang.*; // Import Language package import java.util.*; // Import Utility package to accept data class SimpleInterest { int amount; // data member declaration float rate; float years; double SI; SimpleInterest(int a, float r, float y) // Constructor to initialize data members { amount = a; rate = r; years = y; } void calSI() // method to calculate simple interest { SI = (amount*rate*years)/100; System.out.println("Simple Interest = "+SI); } public static void main(String args[]) { Scanner s = new Scanner(System.in); System.out.print("Enter Principal Amount :: "); int amt = s.nextInt(); // Converting string to int System.o...

Program to define a class Tender containing data members cost and company name. Accept data for five objects and display company name for which cost is minimum

This program demonstrates you the array of objects.  Array of object  is the collection of objects of the same class.The given syntax will define an array of reference therefore assign object to individual reference in the array to declare the array of object. The syntax to define array of object is: <class-name> <array-name> [size]; For example, the following statement will define an array of object having size 6 references to the class  Box . Box b[6]; The above statement just declare array of objects. For creating an array of objects (allocating memory) you have to write down the following statements for (int i=0; i<6; i++) { b[i] = new Box( ); // Assigning object to individual reference in the array. } You can access the members of particular object by using membership operator like: b[i].length = 10; b[i].width = 20; b[i].height = 30; PROGRAM import java.io.BufferedReader; import java.io.IOException; import java.io.Inpu...

Program to define a class Item containing code and price. Accept this data for five object using array of objects. Display code, price in tabular form and also, display total price of all items

This program demonstrates you the array of objects.  Array of object  is the collection of objects of the same class. The given syntax will define an array of reference therefore assign object to individual reference in the array to declare the array of object. The syntax to define array of object is: <class-name> <array-name> [size]; For example, the following statement will define an array of object having size 6 references to the class  Box . Box b[6]; The above statement just declare array of objects. For creating an array of objects (allocating memory) you have to write down the following statements for (int i=0; i<6; i++) { b[i] = new Box( ); // Assigning object to individual reference in the array. } You can access the members of particular object by using membership operator like: b[i].length = 10; b[i].width = 20; b[i].height = 30; PROGRAM import java.io.BufferedReader; import java.io.IOException; import java.io.InputStr...

Program for Abstract class and Abstract method

An  abstract class  is a class that cannot be instantiated. When a method is declared as "abstract" in a class it must be overridden by the subclass of the super classes which contain that method. An  abstract method  does not have body. Body of an abstract method will be defined by subclass. To declare an  abstract method  use the following form: abstract return-type <method-name> (parameter-list); Any class that contains one or more abstract methods must also be declared as abstract. That is, an abstract class cannot be directly instantiated with the new operator. abstract class <class-name> { // abstract method abstract return-type <method-name>( ); // concrete or non-abstract method return-type <method-name>( ); } In below program,  LivingThing  is an  abstract class  which contains one  abstract method  called  walk( )  and two concrete methods  breath( ), eat( ) ...

Program to demonstrate the use of 'final' keyword

In Java, the  final  keyword is used for three purposes: It is used to declare a variable as a constant. It is used to prevent method overriding. It is used to prevent inheritance. We can declare a variable in any scope to be  final . The value of final variable cannot change after it has been initialized. To declare a final variable, we use the  final  keyword in the variable declaration before the types. final type <variable-name> = value; PROGRAM class A { void show() { System.out.println("Inside A"); } } class B extends A { final double PI = 3.14; int x = 10; void show() { System.out.println("Inside B"); x = 20; System.out.println("x = "+x); System.out.println("PI = "+PI); } public static void main(String args[]) { B objB = new B(); objB.show(); A objA = new A(); objA.show(); } } OUTPUT C:\>javac B.java C:\>java B Inside B x = 20 PI = 3.14 Inside A

Program to use 'super' keyword to overcome name hiding

The  super  keyword is used to access base class constructor, variable and methods. A subclass can also explicitly call a constructor of its immediate super class. This is done by using the  super  keyword. The super keyword is used in following conditions: super  may only be used within a subclass constructor or method. The class of superclass constructor must appear as the first statement within the subclass constructor. The parameters in the super call must match the order and type of the instance variable declared in the superclass. super (parameter-list); Super has two general forms: The first calls the superclass's constructor. The second is used to access a member (variable or method) of the superclass that has been declared as private. In this program, we have declare  ClassA  which has a single variable  i .  ClassB  extends  ClassA  which also have variable  i . In its constructor we have ca...

Program to demonstrate the constructor calling order

A  Constructor  is a special type of method which enables to initialize an object when it is first created. It has the same name as the class name in which it is declared. It does not specify a return type not even void. Constructor may be  default constructor  or  paramerized constructor . It has following syntax: // Default constructor <class-name> ( ) { // Statements } OR // Parameterized constructor <class-name> (parameter list) { // Statements } When the class hierarchy in multilevel inheritance is created, there is a sequence in which the default constructors are called. Constructors are always called in the order of derivation from super class to subclass. This order does not change though the ‘super ( )’ is used or not used. If super ( ) is not used, then the default constructor of each super class will be executed. In below program when you will create an object of  C  then the A's constructor is invoked first the...

Program to implement Method Overriding for following inheritance

When a superclass and subclass both have a method having same name and same type signatures (same return type and number of arguments with same data types) then the method in the subclass is said to be  override  the method of superclass. In this program  area( )  is a method of superclass  Shape  which have same method name, same return type and no arguments is overridden in subclasses  Rectangle  and  Triangle . When a overridden method is called from within a subclass then it always calls the method in subclass, whereas the method defined in superclass will be hidden. An  abstract class  is a class that cannot be instantiated. When a method is declared as "abstract" in a class it must be overridden by the subclass of the super classes which contain that method. An  abstract method  does not have body. Body of an abstract method will be defined by subclass. To declare an  abstract method  use the follo...

Program to accept a string from the console and count number of vowels, consonants, digits, tabs and blank spaces in a string

In this program, we have to get a string from user and display the number of vowels, consonants, digits, tabs and blank spaces in that string. To accomplish this we first read a string from keyboard. After that we take a single character at a time upto the last character in given string and compare it for vowel, consonant, digit, tab and blank spaces. For examlple, let us consider the string "abc". In this string we first read the character 'a', then we read character 'b' and finally we read character 'c' Then we will get output as below: Number of vowels: 1 Number of consonants: 2 The logic for this is given in the program. PROGRAM import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Vowels { public static void main(String args[]) throws IOException { String str; int vowels = 0, consonants = 0, digits = 0, tabs = 0, blanks_spaces = 0, other = 0; char ch; BufferedReader br = new B...

Program to show use of some 'StringBuffer' class methods

A  StringBuffer  class is like a String, but can be modified. StringBuffer class is mutable. StringBuffer is fast and consumes less memory when you concat strings. For example, // Constructs string buffer with no characters in it // and an initial capacity of 16 characters. StringBuffer s1 = new StringBuffer( ); OR // Constructs a string buffer with no characters in it and the specified // initial capacity to 5. StringBuffer s2 = new StringBuffer(5); // Constructs a string buffer that contains the three characters. // The initial capacity of the string buffer is 16 plus // the length of the "abc" string in short it is 19. StringBuffer s3 = new StringBuffer("abc"); We have used the following methods of  StringBuffer  class: capacity( ) :  It returns the current capacity. lastIndexOf(String str) :  It returns the index within this string of the rightmost occurrence of the specified substring. reverse( ) :  It causes the characte...

Implement a program to accomplish the following task using string / string Buffer class.

In this program, we will do the following: Accept a password from user. Check if password is correct then display "Good" Else display "Incorrect password" Append the password with the string "Welcome to java!!!" Display the password in reverse order. Replace the character '!' in password with "*" character. We use  String  class and  StringBuffer  class to accomplish this task. The  String  class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are immutable. Strings are constant; their values cannot be changed after they are created. For example: String str = "abc"; // Creates a string literal OR String str = new String("abc"); A  StringBuffer  class is like a String, but can be modified. StringBuffer class is mutable. StringBuffer is fast and consumes less memory when you concat strings. For example, ...

Program to show use of some of 'String' class methods

The  String  class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are immutable. Strings are constant; their values cannot be changed after they are created. For example: String str = "abc"; // Creates a string literal OR String str = new String("abc"); In this program we have used the following methods of  String  class: length( ) :  It returns the length of this string. replace(CharSequence target, CharSequence replacement) :  It replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. : concat(String str) :  It concatenates the specified string to the end of this string. PROGRAM public class UsingStringMethods { public static void main(String[] args) { int n; String s = "Java programming", t = "", u = ""; System.out.println(s)...

Program to find all substrings of a string and print them. For example substrings of "fun" are:- "f", "fu", "fun", "u", "un","n". Use substring method of String class to find substring

The  String  class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class. Strings are immutable. Strings are constant; their values cannot be changed after they are created. For example: String str = "abc"; // Creates a string literal OR String str = new String("abc"); Here we have used the String class's method  length( )  which returns the length of string. The method  substring(int beginIndex, int endIndex)  returns a new string that is a substring of this string. We have created a string and divide that string into subparts which are shown in output. PROGRAM import java.util.Scanner; public class SubStringsOfString { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.println("Enter some string:"); String str = s.nextLine(); System.out.println("Substrings of '"+ str + "' are... ...