JAVA PROGRAMS

Share Embed Donate


Short Description

Download JAVA PROGRAMS...

Description

JAVA PROGRAMS

JAVA PROGRAMS [1]: JAVA STRING - Programming Examples [2]: JAVA ARRAYS-Programming Examples [3]: JAVA DATE & TIME-Programming Example [4]: JAVA METHODS-Programming Examples [5]: JAVA FILES -Programming Examples [6]: JAVA DIRECTORY -Programming Examples [7]: JAVA EXCEPTION - Programming Examples [8]: JAVA DATA STRUCTURE - Programming Examples [9]: JAVA COLLECTION - Programming Examples [10]: JAVA THREADING -Programming Examples [11]: JAVA APPLET - Programming Examples [12]: JAVA SIMPLE GUI - Programming Examples [13]: JAVA JDBC - Programming Examples [14]: JAVA REGULAR EXPRESSION - Programming Examples [15]: JAVA NETWORK - Programming Examples [16]: TCS JAVA Programs Assignment [17]: SOME MORE IMPORTANT PROGRAMS

[email protected]

Page 1

JAVA PROGRAMS [1]: JAVA STRING - PROGRAMMING EXAMPLES

[1]: How to compare two strings? Solution: Following example compares two strings by using str compareTo (string) , str compareToIgnoreCase(String) and str compareTo(object string) of string class and returns the ascii difference of first odd characters of compared strings . public class StringCompareEmp{ public static void main(String args[]){ String str = "Hello World"; String anotherString = "hello world"; Object objStr = str; System.out.println( str.compareTo(anotherString) ); System.out.println( str.compareToIgnoreCase(anotherString) ); System.out.println( str.compareTo(objStr.toString())); } }

Result: The above code sample will produce the following result. -32 0 0

[2]: How to search the last position of a substring? Solution: This example shows how to determine the last position of a substring inside a string with the help of strOrig.lastIndexOf(Stringname) method. public class SearchlastString { public static void main(String[] args) { String strOrig = "Hello world ,Hello Reader"; int lastIndex = strOrig.lastIndexOf("Hello"); if(lastIndex == - 1){ System.out.println("Hello not found"); }else{ System.out.println("Last occurrence of Hello is at index "+ lastIndex); } } }

Result: The above code sample will produce the following result. Last occurrence of Hello is at index 13

[3]: How to remove a particular character from a string?

[email protected]

Page 2

JAVA PROGRAMS Solution: Following example shows hoe to remove a character from a particular position from a string with the help of removeCharAt(string,position) method public class Main { public static void main(String args[]) { String str = "this is Java"; System.out.println(removeCharAt(str, 3)); } public static String removeCharAt(String s, int pos) { return s.substring(0, pos) + s.substring(pos + 1); } }

Result: The above code sample will produce the following result. thi is Java

[4]: How to replace a substring inside a string by another one? Solution: This example describes how replace method of java String class can be used to replace character or substring by new one. public class StringReplaceEmp{ public static void main(String args[]){ String str="Hello World"; System.out.println( str.replace( 'H','W' ) ); System.out.println( str.replaceFirst("He", "Wa") ); System.out.println( str.replaceAll("He", "Ha") ); } }

Result: The above code sample will produce the following result. Wello World Wallo World Hallo World

[5]: How to reverse a String? Solution: Following example shows how to reverse a String after taking it from command line argument .The program buffers the input String using StringBuffer(String string) method, reverse the buffer and then converts the buffer into a String with the help of toString() method. public class StringReverseExample{ public static void main(String[] args){ String string="abcdef"; String reverse = new StringBuffer(string). reverse().toString(); System.out.println("\nString before reverse: "+string); System.out.println("String after reverse: "+reverse); } }

Result: The above code sample will produce the following result. String before reverse:abcdef

[email protected]

Page 3

JAVA PROGRAMS String after reverse:fedcba

[6]: How to search a word inside a string? Solution: This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise it returns -1. public class SearchStringEmp{ public static void main(String[] args) { String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1){ System.out.println("Hello not found"); }else{ System.out.println("Found Hello at index " + intIndex); } } }

Result: The above code sample will produce the following result. Found Hello at index 0

[7]: How to split a string into a number of substrings? Solution: Following example splits a string into a number of substrings with the help of str split(string) method and then prints the substrings. public class JavaStringSplitEmp{ public static void main(String args[]){ String str = "jan-feb-march"; String[] temp; String delimeter = "-"; temp = str.split(delimeter); for(int i =0; i < temp.length ; i++){ System.out.println(temp[i]); System.out.println(""); str = "jan.feb.march"; delimeter = "\\."; temp = str.split(delimeter); } for(int i =0; i < temp.length ; i++){ System.out.println(temp[i]); System.out.println(""); temp = str.split(delimeter,2); for(int j =0; j < temp.length ; j++){ System.out.println(temp[i]); } } } }

Result: The above code sample will produce the following result. Jan feb

[email protected]

Page 4

JAVA PROGRAMS march jan jan jan feb.march feb.march feb.march

[8]: How to convert a string totally into upper case? Solution: Following example changes the case of a string to upper case by using String toUpperCase() method. public class StringToUpperCaseEmp { public static void main(String[] args) { String str = "string abc touppercase "; String strUpper = str.toUpperCase(); System.out.println("Original String: " + str); System.out.println("String changed to upper case: " + strUpper); } }

Result: The above code sample will produce the following result. Original String: string abc touppercase String changed to upper case: STRING ABC TOUPPERCASE

[9]: How to match regions in strings? Solution: Following example determines region matchs in two strings by using regionMatches() method. public class StringRegionMatch{ public static void main(String[] args){ String first_str = "Welcome to Microsoft"; String second_str = "I work with Microsoft"; boolean match = first_str. regionMatches(11, second_str, 12, 9); System.out.println("first_str[11 -19] == " + "second_str[12 - 21]:-"+ match); } }

Result: The above code sample will produce the following result. first_str[11 -19] == second_str[12 - 21]:-true

[10]: How to compare performance of string creation? Solution: Following example compares the performance of two strings created in two different ways. public class StringComparePerformance{ public static void main(String[] args){ long startTime = System.currentTimeMillis();

[email protected]

Page 5

JAVA PROGRAMS for(int i=0;i = amount or return 0 otherwise. Solution: static int output;

// variables are defined at class level

public static void deposit(int amount, int balance) // performs deposit calculation { output = amount + balance; } public static void withdraw(int amount, int balance) // performs withdraw calculation { output = balance - amount; if (balance >= amount) { System.out.println(":::Inside the WithDraw method :::"); } else { System.out.println(":::Inside the WithDraw method :::"); output = 0; } }

[email protected]

Page 140

JAVA PROGRAMS public static void main(String[] args) { int amount, balance; // local variables BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); try { System.out.println("\t\t BANK ::::::::"); System.out.println("Enter the Amount value: "); amount = Integer.parseInt(in.readLine()); // Input value from keyboard for amount value System.out.println("Enter the Balance value: "); balance = Integer.parseInt(in.readLine()); // Input value from keyboard for balance value deposit(amount, balance); // deposit method called for computation System.out.println(":::Inside the Deposit method :::"); System.out.println("New Balance:::" + output); withdraw(amount, balance); // withdraw method called for compu System.out.println("New Balance:::" + output); } catch (Exception e) { System.out.println("Error:::" + e); } }

[11]: Create an Employee class which has methods netSalary which would accept salary & tax as arguments & returns the netSalary which is tax deducted from the salary. Also it has a method grade which would accept the grade of the employee & return grade. Solution: import java.util.*; class Employee { public double netSalary(double salary, double taxrate){ double tax=salary*taxrate; double netpay=salary=tax; return netpay; } public static void main(String[] args) { Employee emp=new Employee(); Scanner input=new Scanner(System.in); System.out.print("Enter Salary: "); double sal=input.nextDouble(); System.out.print("Enter Tax in %: "); double taxrate=input.nextDouble()/100; double net=emp.netSalary(sal,taxrate); System.out.println("Net Salary is: "+net); } }

[12]: Create Product having following attributes: Product ID, Name, Category ID and UnitPrice. Create ElectricalProduct having the following additional attributes: VoltageRange and Wattage. Add a behavior to change the Wattage and price of the electrical product. Display the updated ElectricalProduct details Solution:

[email protected]

Page 141

JAVA PROGRAMS import java.util.*; class Product{ int productID; String name; int categoryID; double price; Product(int productID,String name,int categoryID,double price){ this.productID=productID; this.name=name; this.categoryID=categoryID; this.price=price; } } public class ElectricalProduct extends Product{ int voltageRange; int wattage; ElectricalProduct(int productID,String name,int categoryID,double price,int voltageRange, int wattage){ super(productID,name,categoryID,price); this.voltageRange=voltageRange; this.wattage=wattage; } public void display(){ System.out.println("Product ID: "+productID); System.out.println("Name: "+name); System.out.println("Category ID: "+categoryID); System.out.println("Price: "+price); System.out.println("Voltage Range: "+voltageRange); System.out.println("Wattage: "+wattage); } public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Enter Product ID: "); int pid=input.nextInt(); System.out.println("Enter Name: "); String name=input.next(); System.out.println("Enter Catagory ID: "); int cid=input.nextInt(); System.out.println("Enter Price: "); double price=input.nextDouble(); System.out.println("Enter Voltage Range: "); int vrange=input.nextInt(); System.out.println("Enter Wattage: "); int wattage=input.nextInt(); System.out.println("****Details of Electrical Product****"); System.out.println(); ElectricalProduct p=new ElectricalProduct(pid,name,cid,price,vrange,wattage); p.display(); } }

[13]: Create Book having following attributes: Book ID, Title, Author and Price. Create Periodical which has the following additional attributes: Period (weekly, monthly etc...) .Add a behavior to modify the Price and the Period of the periodical. Display the updated periodical details. Solution: [email protected]

Page 142

JAVA PROGRAMS import java.util.*; class Book{ int id; String title; String author; double price; public void setId(int id){ this.id=id; } public int getId(){ return id; } public void setTitle(String title){ this.title=title; } public String getTitle(){ return title; } public void setAuthor(String author){ this.author=author; } public String getAuthor(){ return author; } public void setPrice(double price){ this.price=price; } public double getPrice(){ return price; } } class Periodical { String timeperiod; public void setTimeperiod(String timeperiod){ this.timeperiod=timeperiod; } public String getTimeperiod(){ return timeperiod; } } public class BookInformation{ public static void main(String[]args){ Book b=new Book(); Periodical p=new Periodical(); Scanner input=new Scanner(System.in); System.out.print("Book ID: "); int id=input.nextInt(); b.setId(id); System.out.print("Title: "); String title=input.next(); b.setTitle(title); System.out.print("Author: "); String author=input.next(); b.setAuthor(author); System.out.print("Price: "); double price=input.nextDouble(); b.setPrice(price); System.out.print("Period: ");

[email protected]

Page 143

JAVA PROGRAMS String pp=input.next(); p.setTimeperiod(pp); System.out.println(); System.out.println("----Book Information----"); System.out.println(); System.out.println("Book ID: "+b.getId()); System.out.println("Title: "+b.getTitle()); System.out.println("Author: "+b.getAuthor()); System.out.println("Price: "+b.getPrice()); System.out.println("Period: "+p.getTimeperiod()); } }

[14]: Create Vehicle having following attributes: Vehicle No., Model, Manufacturer and Color. Create truck which has the following additional attributes: loading capacity (100 tons?).Add a behavior to change the color and loading capacity. Display the updated truck details. Solution: import java.util.*; class Vehicle { int no; String model; String manufacturer; String color; Vehicle(int no,String model,String manufacturer,String color){ this.no=no; this.model=model; this.manufacturer=manufacturer; this.color=color; } } public class Truck extends Vehicle{ int capacity; Truck(int no,String model,String manufacturer,String color,int capacity){ super( no, model, manufacturer, color); this.capacity=capacity; } void show(){ System.out.println("No = " + no); System.out.println("Model = " + model); System.out.println("manufacturer = " + manufacturer); System.out.println("Color = " + color); System.out.println("Capacity = " + capacity); } public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("Truck No: "); int no=input.nextInt(); System.out.println("Model: "); String model=input.next(); System.out.println("Manufacturer: "); String manufacturer=input.next();

[email protected]

Page 144

JAVA PROGRAMS

System.out.println("Color: "); String color=input.next(); System.out.println("Loading Capacity: "); int cap=input.nextInt(); Truck t=new Truck(no,model,manufacturer,color,cap); System.out.println("****Truck Details****"); System.out.println(); t.show(); } }

[15]: Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the results. Solution: import java.util.*; import java.text.*; class NumberProgram { public static void main(String[] args) { DecimalFormat df=new DecimalFormat("##.##"); Scanner input=new Scanner(System.in); System.out.print("Enter Number: "); double num=input.nextDouble(); System.out.print("Raise Number's power: "); double pow=input.nextDouble(); double value=Math.pow(num,pow); System.out.println("Result is: "+df.format(value)); } }

[16]: Write a function Model-of-Category for a Tata motor dealers, which accepts category of car customer is looking for and returns the car Model available in that category. the function should accept the following categories "SUV", "SEDAN", "ECONOMY", and "MINI" which in turn returns "TATA SAFARI" , "TATA INDIGO" , "TATA INDICA" and "TATA NANO" respectively. Solution: import java.util.*; class TataMotors{ String category; String model; TataMotors(String category,String model){ this.category=category; this.model=model; } public String getCategory(){ return category; } public String getModel(){ return model; }

[email protected]

Page 145

JAVA PROGRAMS public static void ModelOfCategory(ArrayList list){ Scanner input=new Scanner(System.in); System.out.print("Enter Category: "); String category=input.nextLine(); System.out.println(); System.out.print("Model is: "); for (TataMotors tm : list){ if(tm.getCategory().equals(category)){ System.out.print(tm.getModel()); } } } public static void main(String[] args) { ArrayList list=new ArrayList(); list.add(new TataMotors("SUV","TATA SAFARI")); list.add(new TataMotors("SEDAN","TATA INDIGO")); list.add(new TataMotors("ECONOMY","TATA INDICA")); list.add(new TataMotors("MINI","TATA NANO")); }

ModelOfCategory(list);

}

[17]: Create a washing machine class with methods as switchOn, acceptClothes, acceptDetergent, switchOff. acceptClothes accepts the noofClothes as argument & returns the noofClothes Solution: public class WashingMachine{ public void switchOn(){ } public int acceptClothes(int noofClothes){ return noofClothes; } public void acceptDetergent(){ } public void switchOff(){ } public static void main(String[] args){ WashingMachine wm = new WashingMachine(); wm.switchOn(); int clothesAccepted = wm.acceptClothes(10); wm.acceptDtergent(); wm.switchOff(); } }

[18]: Create a class called Student which has the following methods: I. Average: which would accept marks of 3 examinations & return whether the student has passed or failed depending on whether he has scored an average above 50 or not. ii. Inputname: which would accept the name of the student & returns the name. [email protected]

Page 146

JAVA PROGRAMS Solution: import java.util.*; public class Student{ Scanner input=new Scanner(System.in); public String average(){ System.out.print("Enter Marks1: "); double m1=input.nextDouble(); System.out.print("Enter Marks2: "); double m2=input.nextDouble(); System.out.print("Enter Marks3: "); double m3=input.nextDouble(); double tm=m1+m2+m3; double avg=tm/3; if(avg50){ return "Passed"; } return " "; } public String getName(){ System.out.println("Enter Name:"); String name=input.nextLine(); String result=average(); return name+" get "+result; } public static void main(String[]args){ Student data=new Student(); String nameAndResut=data.getName(); System.out.println(nameAndResut); } }

[19]: Create a calculator class which will have methods add, multiply, divide & subtract. Solution: class Calculation{ public int add(int a,int b){ return a+b; } public int subtract(int a,int b){ if(a>b){ return a-b; } else{ return b-a; } } public int multiply(int a,int b){ return a*b; } public int divide(int a,int b){ if(a>b){ return a/b; } else{

[email protected]

Page 147

JAVA PROGRAMS return b/a; } } } public class Calculator{ public static void main(String []args){ Calculation cal=new Calculation(); int add=cal.add(5,10); int sub=cal.subtract(5,10); int mul=cal.multiply(5,10); int div=cal.divide(5,10); System.out.println(add); System.out.println(sub); System.out.println(mul); System.out.println(div); } }

[17]: SOME MORE IMPORTANT PROGRAMS [1]: Write a program for the following output: 1 2 3 4 5 3 5 7 9 8 12 16 20 28 48

Solution: class PrintDemo{ public static void main(String args[]) { int i=0,j=0,n=5; int a[]=new int[50]; for(i=0;i0;i--) { System.out.println(); for(j=0;j
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF