Code 9: Many Methods & Instances
Code a:
import java.util.Scanner;
public class Test{
public static void main(String args[]){
Class2 Class2obj = new Class2();
Scanner input = new Scanner(System.in);
System.out.println("Enter your name");
String name = input.nextLine();
Class2obj.setName(name);
Class2obj.message();
}
}
Code b:
public class Class2 {
private String gname;
public void setName(String name){
gname = name;
}
public String getname(){
return gname;
}
public void message(){
System.out.printf(" Do you Remember ! Your first gf was %s" , getname());
}
}
Code 10: Constructors
What is Constructor:
Initialize a variable as soon as an object is created.
Code a:
import java.util.Scanner;
public class Test{
public static void main(String args[]){
Class2 Class2obj = new Class2("Debra");
Class2obj.message();
}
}
Code b:
public class Class2 {
private String gname;
public Class2(String name){
gname = name;
}
public String getname(){
return gname;
}
public void message(){
System.out.printf(" Do you Remember ! Your first gf was %s" , getname());
}
}
Code 11: Nested if Statements
import java.util.Scanner;
public class Test{
public static void main(String args[]){
Scanner iage = new Scanner(System.in);
System.out.println("Hey ! Welcome . To check if you can Retire, enter your age");
int age = iage.nextInt();
if (age < 60){
System.out.println("You are young mate. Do some Work.");
}
else{
System.out.println("You are Old. You can Retire. Let me check......");
if (age >75){
System.out.println("You can retire immediately .");
}
else {
System.out.println("You can retire in some years to come...");
}
}
}
}
Code 12: Else if Statements
import java.util.Scanner;
public class Test{
public static void main(String args[]){
Scanner iage = new Scanner(System.in);
System.out.println("Hey ! Lets see if you are studuing in school, pursuing graduation or working");
int age = iage.nextInt();
if (age <= 18){
System.out.println("You are probably in school.");
}
else if (age>18 && age <=20)
{
System.out.println("You are probably pursuing your graduation.");
}
else if (age >20 && age <75){
System.out.println("You are probably working.");
}
else{
System.out.println("You are too Old to work. You should Retire.");
}
}
}
No comments:
Post a Comment