Java program to print Hello World and demonstrate variable types
1. /*
* The first program will print a sentance on the screen "hallo world"
*/
package hallo;
public class Hallo {
public static void main(String[] args) /*this is the start point for the every Java program. it is fixed*/
{
String firstprogram = " Hello world";
System.out.println("Hallo BolyTech students"); /*short cut for that is sout + tab*/
System.out.println("firstprogram = " + firstprogram); /*the shout cut for that is soutv + tab*/
}
}
/*
second program show the type of variable used in JAVA and how to print Ascii code
*/
package variable;
public class Variable {
public static void main(String[] args)
{
byte b=127; // 8 bits signed
short s=32000; // 16 bits signed
int i=200; // 32 bits signed
long L=200; // 64 bits signed
float f=2.5f; // 32 bits single-precision suiable for currency
double d=2.5; // 64 bits double-precision
char c='A'; // 16 bits
2. boolean flag=false; // 1 bit true or false
int decimal=100;
int octal = 0144; /*how to write num in octa */
int hexa= 0x64; /*how to write num in hexa*/
int x=0; // it should has initial value
String str="Java case sensetive";
System.out.println("byte type: " + b);
System.out.println("short type: " + s);
System.out.println("long type: " + L);
System.out.println("float type: " + f);
System.out.println("double type: " + d);
System.out.println("char type: " + c);
System.out.println("boolean type: " + flag);
System.out.println("string type: " + str);
System.out.print("Octa Type " + octal+"n");
System.out.print("hexa Type " +hexa+"n");
System.out.println(" x "+x);
// n t " ' these are also useful to arrange the output text
char y=97;
System.out.println("asci a =" +y); // how to print Ascii code
for (y = 97; y < 100; y++) {
System.out.println("Ascii " + y);
} } }
3. /*third program used to deal with Scanner library.
you can read more about it using this link
http://www.tutorialspoint.com/java/util/java_util_scanner.htm*/
package scannerlibrary;
import java.util.Scanner; /*to import the library to deal read from screen*/
public class ScannerLibrary {
public static void main(String[] args)
{
// test about Scanner library
Scanner input = new Scanner(System.in); /*create a new scanner to read from screen*/
System.out.println("enter your name : ");
String name=input.next();
System.out.println(name);
System.out.println("enter your name : " + input.next()); // short way to do the last three sentence
}
}
/*
scan two integer number and gives the sum
*/
package scanner_int_num;
import java.util.Scanner;
public class Scanner_int_num {
public static void main(String[] args) {
Scanner myobject= new Scanner (System.in);
System.out.println("enter first num ");
4. int num1=myobject.nextInt();
System.out.println("enter Second num");
int num2=myobject.nextInt();
System.out.println("sum = " + (num1+num2) );
}
}
/*
more about Scanner used
*/
package scannerstring;
import java.util.Scanner;
public class ScannerString {
public static void main(String[] args) {
String s = "Hello World 3 + 3.0 = 6 ";
// create a new scanner with the specified String Object
Scanner str = new Scanner(s);
// find the next token and print it
System.out.println(str.next());
// find the next token and print it
System.out.println(str.next());
System.out.println(str.next());
System.out.println(str.next());
System.out.println(str.next());
System.out.println(str.next());
System.out.println(str.next());
// close the scanner
str.close(); } }
5. Constructor:
- Each class has a constructor whether define or not. It is use to initialize all variables to zero.
- Each time a new object invoked, at least one constructor will be invoked.
- Constructor does not have return value.
- Main rule of constructor it should has the same name of the class.
- How to call a constructor?
( name_of_class variable_name = new constructor_name)
Scanner input = new Scanner();
Example (1):
Simple example that uses a constructor without parameters:
class Car{
int x;
Car( ){
x = 10;
}
}
public class ConstrutorTest {
public static void main(String[] args) {
Car mycar= new Car();
System.out.println("x = "+ mycar.x);
}
}
Example (2):
Here is a simple example that uses a constructor with parameter:
class Car{
int x;
Car(int i){
x = i;
}
}
public class ConstrutorTest {
public static void main(String[] args) {
Car mycar= new Car(12);
6. System.out.println("x = "+ mycar.x);
}
}
Example (3):
Uses of default and parameter constructor
public class Example
{
int x;
public Example()
{
//code for default one
x= 10;
}
public Example(int num)
{
//code for parameterized one
x = num;
}
public int getValue()
{
return x;
}
}
7. Example (4) of Constructor Overloading
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[]){
Student s1 = new Student (12,"Ahmed");
Student s2 = new Student (22,"Ali",25);
s1.display();
s2.display();
}
}
8. // example about overloaded constructer
package construtortest;
class Example
{
int var;
protected Example()
{
//code for default one
var = 10;
System.out.print("default constractor ");
}
public Example(int num)
{
//code for parameterized one
var = num;
System.out.print("constractor with one int ");
}
public Example(double num)
{
//code for parameterized one double
var = (int)num;
System.out.print("constractor with one doubel ");
}
public int getValue()
{
return var;
}}
9. public class ConstrutorTest {
public static void main(String[] args) {
Example obj1= new Example();
System.out.println(+obj1.getValue());
obj1= new Example(12);
System.out.println(+obj1.getValue());
obj1= new Example(20.6);
System.out.println(+obj1.getValue());
} }
Inheritance:
Example (1): to understand super class and sub class :
package inheritance;
class super_class {
super_class(){
System.out.println("super class");
}
}
public class sub_class extends super_class{
public sub_class () {
super();
System.out.println("sub class");
}
public static void main(String[] args) {
sub_class supclass = new sub_class ();
} }
10. //example of super keyword
class Vehicle{
int speed=50;
}
class Bike4 extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike4 b=new Bike4();
b.display();
}
}
Output:50
11. class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
}
}
Output:
Vehicle is created
Bike is created
12. class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike6 extends Vehicle{
int speed;
Bike6(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike6 b=new Bike6(10);
}
}
Output:Vehicle is created
10
13. class Person{
void message(){System.out.println("welcome");}
}
class Student16 extends Person{
void message(){System.out.println("welcome to java");}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student16 s=new Student16();
s.display();
}
}
Output:welcome to java
welcome
14. Example (2):
package arraytest;
import java.util.Scanner;
class arrayone
{
protected int a[]=new int[6];
}
class arraytwo extends arrayone
{
public void set()
{ System.out.println("Enter the elements of array : ");
Scanner input= new Scanner(System.in);
for (int i = 0; i <6; i++) {
System.out.print("a["+i+"]=");
a[i]=input.nextInt();
}}
public void display()
{
System.out.print("The elemnts of a = ");
for (int i = 0; i <6; i++) {
System.out.print(a[i]+" ");
}}
public class Arraytest {
public static void main(String[] args) {
arraytwo two=new arraytwo();
two.set();
two.display(); }}
15.
16. package firstdigitchange;
public class FirstDigitChange {
public static void main(String[] args) {
// TODO code application logic here
int x=7458;
int t=1;
int s=0,x2=0;
int num=2;
x2=x;
while(x2>=10){
x2=x2/10;
t=t*10;
}
num=num*t+(x%t);
System.out.println("after change "+ num);
}
}
17. //practical exam solution :
package exam;
import java.util.Scanner;
class Deparments
{
private String[]Names=new String[5];
public String GetDepName(int i)
{
try
{
return Names[i];
}
catch(IndexOutOfBoundsException e)
{
return "error ";
}
}
public void SetDepNames()
{
Scanner S=new Scanner(System.in);
System.out.println("Set elements to your array:");
18. for (int i = 0; i < 5; i++)
{
System.out.print("a["+i+"]=");
Names[i]=S.next();
}
}
}
class Employee extends Deparments
{
private String Name;
private int DepID;
private double Salary;
public void SetEmpName(String i)
{
Name=i;
}
public void SetSalary(double i)
{
Salary=i;
}
public void SetDepID(int i)
{
DepID=i;
19. }
public String GetEmpName()
{
return Name;
}
public double GetSalary()
{
return Salary;
}
public int GetDepID()
{
return DepID;
}
}
public class Exam
{
public static void main(String[] args)
{
try
{
Employee A1=new Employee();
Employee A2=new Employee();
Employee A3=new Employee();
22. Applet
1. Write a program using java language to create a class called Example inherited by Applet class
then prints “Hello world” on the applet form.
Solution:
Click the File tab then click New Project as shown below:
Then from Categories choose Java and from Projects choose Java Application then click Next.
Then click Finish.
23. Then click New File as shown below:
Then from Categories choose Java and from File Types choose Java Class then click Next.
24. Then from Class Name Type Example then click Finish.
Then type these codes inside the class as shown below:
25. To run your file, from menu strip, click Run then choose Run File.
After file has been ran this form should appear like below:
26. 2. Write a program using java language to create a JApplet Form then add three tools in it:
a. Text Field.
b. Combo Box.
c. Button.
Type a code when the user clicks Button, the text in the combo Box should appears in the Text
Field.
Solution:
Click the File tab then click New Project as shown below:
Then from Categories choose Java and from Projects choose Java Application then click Next.
28. Then from Categories choose Swing GUI Forms and from File Types choose JApplet Form then
click Next.
Then click Finish.
29. Then from Palette add Button, Text Field and Combo Box on the JApplet Form.
The form should be look like below:
30. Then press double click on the button and type these codes in it.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText(jComboBox1.getSelectedItem().toString());
}
3. Write a program using java language to create a JApplet Form, which draw lines when the user
press on it and dragged.
Solution:
Click the File tab then click New Project as shown below:
Then from Categories choose Java and from Projects choose Java Application then click Next.
32. Then from Categories choose Swing GUI Forms and from File Types choose JApplet Form then
click Next.
Then click Finish.
33. Then Right Click on the form then Events, Mouse and Click mousePressed
Then type these codes in it.
int x,y;
34. private void formMousePressed(java.awt.event.MouseEvent evt) {
x=evt.getX();
y=evt.getY();
}
Then Right Click on the form then Events, MouseMotion and Click mouseDragged
Then type these codes in it.
private void formMouseDragged(java.awt.event.MouseEvent evt) {
getGraphics().drawLine(x, y, evt.getX(), evt.getY());
x=evt.getX();
y=evt.getY();
}
35. The form should be look like below:
4. Write a program using java language to create a JApplete Form, then add these tools on it:
a. Table.
b. Three Labels
c. Three Text Fields.
d. three Buttons
to be look like below:
The program acts like the following when the user clicks:
a. Add Button: add (Name, Address, Phone) Fields to the table.
b. Edit Button: edit the selected row.
c. Delete Button: delete the selected row from the table
Solution:
36. Click the File tab then click New Project as shown below:
Then from Categories choose Java and from Projects choose Java Application then click Next.
Then click Finish.
37. Then click New File as shown below:
Then from Categories choose Swing GUI Forms and from File Types choose JApplet Form then
click Next.
38. Then click Finish.
Then from Palette add Buttons, Text Fields, Table and Labels on the JApplet Form.
39. After adding table click Right on it then choose Properties:
Then click place of arrow as shown below:
40. Then change Rows to 0 and Columns to 3 and Title to (Name, Address, Phone) as shown below:
Then add the other tools to be look like below:
41. type these codes inside ADD Button:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
t.addRow(new Object[]{jTextField1.getText(),jTextField2.getText(),jTextField3.getText()});
}
type these codes inside Edit Button:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
t.setValueAt(jTextField1.getText(),jTable1.getSelectedRow(),0);
t.setValueAt(jTextField2.getText(),jTable1.getSelectedRow(),1);
t.setValueAt(jTextField3.getText(),jTable1.getSelectedRow(),2);
}
type these codes inside Delete Button:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
t.removeRow(jTable1.getSelectedRow());
}
If you want to use exception , you can change the code to this below:
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
try{
t.removeRow(jTable1.getSelectedRow());}
catch(ArrayIndexOutOfBoundsException e){
JOptionPane.showMessageDialog(rootPane, "please select at least one row " +e);
}
42. //Insert by specific row number:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(Integer.parseInt(jTextField4.getText())>=0
&&Integer.parseInt(jTextField4.getText())<=jTable1.getRowCount())
{
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
String g="Male";
if(jRadioButton2.isSelected())
g="Female";
t.insertRow(Integer.parseInt(jTextField4.getText()), new
Object[]{jTextField1.getText(),jTextField2.getText(),jTextField3.getText(),g});
}
}
// to delete row or more rows
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
if(jTable1.getSelectedRow()!=-1)
t.removeRow(jTable1.getSelectedRow());
}
//For more than one row
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel t=(DefaultTableModel) jTable1.getModel();
while(jTable1.getSelectedRow()!=-1)
t.removeRow(jTable1.getSelectedRow());
}
43. //To search by specific text
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
int count=0;
for (int i = 0; i < jTable1.getRowCount(); i++) {
if(jTable1.getValueAt(i, 2).toString().
equalsIgnoreCase(jTextField4.getText()))
count++;
}
JOptionPane.showMessageDialog(rootPane, "Address="+count);
}
// to update select rows
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTable1.getSelectedRow()!=-1)
{
String g="";
if(jRadioButton1.isSelected())
g="male";
else
g="female";
jTable1.setValueAt(jTextField1.getText(),jTable1.getSelectedRow(), 0);
jTable1.setValueAt(jTextField2.getText(),jTable1.getSelectedRow(), 1);
jTable1.setValueAt(jTextField3.getText(),jTable1.getSelectedRow(), 2);
jTable1.setValueAt(g,jTable1.getSelectedRow(), 3);
}
}